lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
apache-2.0
f6540777f8fb7155da45731935688677a63bb800
0
suninformation/ymateplatform,aglne/ymateplatform
/* * Copyright 2007-2107 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 net.ymate.platform.base; import java.io.InputStream; import java.util.Properties; import net.ymate.platform.base.impl.DefaultModuleLoader; import net.ymate.platform.commons.i18n.I18N; import net.ymate.platform.commons.lang.BlurObject; import net.ymate.platform.commons.util.RuntimeUtils; import org.apache.commons.lang.time.StopWatch; /** * <p> * YMP * </p> * <p> * 框架核心模块管理器; * </p> * * @author 刘镇(suninformation@163.com) * @version 0.0.0 * <table style="border:1px solid gray;"> * <tr> * <th width="100px">版本号</th><th width="100px">动作</th><th * width="100px">修改人</th><th width="100px">修改时间</th> * </tr> * <!-- 以 Table 方式书写修改历史 --> * <tr> * <td>0.0.0</td> * <td>创建类</td> * <td>刘镇</td> * <td>2012-12-23下午5:52:44</td> * </tr> * </table> */ public class YMP { public final static String VERSION = YMP.class.getPackage().getSpecificationVersion(); public final static String BUILD_DATE = YMP.class.getPackage().getImplementationVersion(); public static boolean IS_DEV_MODEL; public static boolean IS_INITED; private static IModuleLoader __MODULE_LOADER; // public static final String __LSTRING_FILE = "net.ymate.platform.base.LocalStrings"; /** * 启动框架初始化 * * @param args */ public static void main(String[] args) { initialize(); } /** * 初始化框架模块 */ public static void initialize() { if (!IS_INITED) { System.out.println(I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.platform_version_show", VERSION, BUILD_DATE)); // Properties _configs = new Properties(); InputStream _in = null; if (RuntimeUtils.isWindows()) { _in = YMP.class.getClassLoader().getResourceAsStream("ymp-conf_WIN.properties"); } else if (RuntimeUtils.isUnixOrLinux()) { _in = YMP.class.getClassLoader().getResourceAsStream("ymp-conf_UNIX.properties"); } if (_in == null) { _in = YMP.class.getClassLoader().getResourceAsStream("ymp-conf.properties"); } if (_in != null) { try { _configs.load(_in); IS_DEV_MODEL = new BlurObject(_configs.getProperty("ymp.dev_model")).toBooleanValue(); __MODULE_LOADER = (IModuleLoader) Class.forName(_configs.getProperty("ymp.module_loader_impl_class")).newInstance(); } catch (Exception e) { __MODULE_LOADER = new DefaultModuleLoader(); } } else { System.err.println(I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.error_load_conf_file")); } StopWatch _stopWatch = new StopWatch(); _stopWatch.start(); try { __MODULE_LOADER.initialize(_configs); IS_INITED = true; } catch (Throwable e) { e.printStackTrace(System.err); } finally { _stopWatch.stop(); if (IS_INITED) { System.out.println(I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.platform_init_successed", _stopWatch.getTime())); } else { System.err.println(I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.platform_init_failed")); } } } } /** * 销毁 */ public static void destroy() { if (IS_INITED && __MODULE_LOADER != null) { try { __MODULE_LOADER.destroy(); } catch (Exception e) { //~~~ } __MODULE_LOADER = null; IS_INITED = false; } } }
ymateplatform/src/main/java/net/ymate/platform/base/YMP.java
/* * Copyright 2007-2107 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 net.ymate.platform.base; import java.io.InputStream; import java.util.Properties; import net.ymate.platform.base.impl.DefaultModuleLoader; import net.ymate.platform.commons.i18n.I18N; import net.ymate.platform.commons.lang.BlurObject; import org.apache.commons.lang.time.StopWatch; /** * <p> * YMP * </p> * <p> * 框架核心模块管理器; * </p> * * @author 刘镇(suninformation@163.com) * @version 0.0.0 * <table style="border:1px solid gray;"> * <tr> * <th width="100px">版本号</th><th width="100px">动作</th><th * width="100px">修改人</th><th width="100px">修改时间</th> * </tr> * <!-- 以 Table 方式书写修改历史 --> * <tr> * <td>0.0.0</td> * <td>创建类</td> * <td>刘镇</td> * <td>2012-12-23下午5:52:44</td> * </tr> * </table> */ public class YMP { public final static String VERSION = YMP.class.getPackage().getSpecificationVersion(); public final static String BUILD_DATE = YMP.class.getPackage().getImplementationVersion(); public static boolean IS_DEV_MODEL; public static boolean IS_INITED; private static IModuleLoader __MODULE_LOADER; // public static final String __LSTRING_FILE = "net.ymate.platform.base.LocalStrings"; /** * 启动框架初始化 * * @param args */ public static void main(String[] args) { initialize(); } /** * 初始化框架模块 */ public static void initialize() { if (!IS_INITED) { System.out.println(I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.platform_version_show", VERSION, BUILD_DATE)); // Properties _configs = new Properties(); InputStream _in = YMP.class.getClassLoader().getResourceAsStream("ymp-conf.properties"); if (_in != null) { try { _configs.load(_in); IS_DEV_MODEL = new BlurObject(_configs.getProperty("ymp.dev_model")).toBooleanValue(); __MODULE_LOADER = (IModuleLoader) Class.forName(_configs.getProperty("ymp.module_loader_impl_class")).newInstance(); } catch (Exception e) { __MODULE_LOADER = new DefaultModuleLoader(); } } else { System.err.println(I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.error_load_conf_file")); } StopWatch _stopWatch = new StopWatch(); _stopWatch.start(); try { __MODULE_LOADER.initialize(_configs); IS_INITED = true; } catch (Throwable e) { e.printStackTrace(System.err); } finally { _stopWatch.stop(); if (IS_INITED) { System.out.println(I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.platform_init_successed", _stopWatch.getTime())); } else { System.err.println(I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.platform_init_failed")); } } } } /** * 销毁 */ public static void destroy() { if (IS_INITED && __MODULE_LOADER != null) { try { __MODULE_LOADER.destroy(); } catch (Exception e) { //~~~ } __MODULE_LOADER = null; IS_INITED = false; } } }
根据运行环境的操作系统类型加载框架配置,优先加载后缀为_WIN或_UNIX的配置(例如:ymp-conf_UNIX.properties),若未提供则默认加载ymp-conf.properties文件
ymateplatform/src/main/java/net/ymate/platform/base/YMP.java
根据运行环境的操作系统类型加载框架配置,优先加载后缀为_WIN或_UNIX的配置(例如:ymp-conf_UNIX.properties),若未提供则默认加载ymp-conf.properties文件
Java
apache-2.0
663943a007b9791f8cce8961921cca3b1627b074
0
hsaputra/cdap,chtyim/cdap,chtyim/cdap,chtyim/cdap,mpouttuclarke/cdap,hsaputra/cdap,caskdata/cdap,caskdata/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,anthcp/cdap,caskdata/cdap,hsaputra/cdap,anthcp/cdap,anthcp/cdap,chtyim/cdap,mpouttuclarke/cdap,caskdata/cdap,hsaputra/cdap,caskdata/cdap,anthcp/cdap,caskdata/cdap,hsaputra/cdap,mpouttuclarke/cdap,anthcp/cdap,chtyim/cdap,chtyim/cdap
/* * Copyright © 2015 Cask Data, 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 co.cask.cdap.data2.transaction.queue; import co.cask.cdap.common.conf.CConfiguration; import co.cask.cdap.common.conf.Constants; import co.cask.cdap.common.queue.QueueName; import co.cask.cdap.data2.datafabric.DefaultDatasetNamespace; import co.cask.cdap.data2.util.hbase.HBaseTableUtil; import co.cask.cdap.proto.Id; /** * Common implementation of table-based QueueAdmin */ public abstract class AbstractQueueAdmin implements QueueAdmin { private final String unqualifiedTableNamePrefix; protected final DefaultDatasetNamespace namespace; public AbstractQueueAdmin(CConfiguration conf, QueueConstants.QueueType type) { // todo: we have to do that because queues do not follow dataset semantic fully (yet) // system scope this.unqualifiedTableNamePrefix = Constants.SYSTEM_NAMESPACE + "." + type.toString(); this.namespace = new DefaultDatasetNamespace(conf); } /** * @param queueTableName actual queue table name * @return namespace id that this queue belongs to */ public static String getNamespaceId(String queueTableName) { // last three parts are namespaceId, appName and flow String[] parts = queueTableName.split("\\."); String namespaceId; if (parts.length == 6) { // cdap.<namespace>.system.queue.<app>.<flow> namespaceId = parts[1]; } else { throw new IllegalArgumentException(String.format("Unexpected format for queue table name. " + "Expected 'cdap.<namespace>.system.queue.<app>.<flow>'" + "Received '%s'", queueTableName)); } return namespaceId; } /** * @param queueTableName actual queue table name * @return app name this queue belongs to */ public static String getApplicationName(String queueTableName) { // last three parts are namespaceId (optional - in which case it will be the default namespace), appName and flow String[] parts = queueTableName.split("\\."); return parts[parts.length - 2]; } /** * @param queueTableName actual queue table name * @return flow name this queue belongs to */ public static String getFlowName(String queueTableName) { // last three parts are namespaceId (optional - in which case it will be the default namespace), appName and flow String[] parts = queueTableName.split("\\."); return parts[parts.length - 1]; } /** * This determines the actual table name from the table name prefix and the name of the queue. * @param queueName The name of the queue. * @return the full name of the table that holds this queue. */ public String getActualTableName(QueueName queueName) { if (queueName.isQueue()) { // <root namespace>.<queue namespace>.system.queue.<app>.<flow> return getTableNameForFlow(queueName.getFirstComponent(), queueName.getSecondComponent(), queueName.getThirdComponent()); } else { throw new IllegalArgumentException("'" + queueName + "' is not a valid name for a queue."); } } protected String getTableNameForFlow(String namespaceId, String app, String flow) { String tablePrefix = getTableNamePrefix(namespaceId); String tableName = tablePrefix + "." + app + "." + flow; return HBaseTableUtil.getHBaseTableName(tableName); } public String getTableNamePrefix(String namespaceId) { // returns String with format: '<root namespace>.<namespaceId>.system.(stream|queue)' String tablePrefix = namespace.namespace(Id.DatasetInstance.from(namespaceId, unqualifiedTableNamePrefix)).getId(); return HBaseTableUtil.getHBaseTableName(tablePrefix); } }
cdap-data-fabric/src/main/java/co/cask/cdap/data2/transaction/queue/AbstractQueueAdmin.java
/* * Copyright © 2015 Cask Data, 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 co.cask.cdap.data2.transaction.queue; import co.cask.cdap.common.conf.CConfiguration; import co.cask.cdap.common.conf.Constants; import co.cask.cdap.common.queue.QueueName; import co.cask.cdap.data2.datafabric.DefaultDatasetNamespace; import co.cask.cdap.data2.util.hbase.HBaseTableUtil; import co.cask.cdap.proto.Id; /** * Common implementation of table-based QueueAdmin */ public abstract class AbstractQueueAdmin implements QueueAdmin { private final String unqualifiedTableNamePrefix; protected final DefaultDatasetNamespace namespace; public AbstractQueueAdmin(CConfiguration conf, QueueConstants.QueueType type) { // todo: we have to do that because queues do not follow dataset semantic fully (yet) // system scope unqualifiedTableNamePrefix = Constants.SYSTEM_NAMESPACE + "." + type.toString(); namespace = new DefaultDatasetNamespace(conf); } /** * @param queueTableName actual queue table name * @return namespace id that this queue belongs to */ public static String getNamespaceId(String queueTableName) { // last three parts are namespaceId, appName and flow String[] parts = queueTableName.split("\\."); String namespaceId; if (parts.length == 6) { // cdap.<namespace>.system.queue.<app>.<flow> namespaceId = parts[1]; } else { throw new IllegalArgumentException(String.format("Unexpected format for queue table name. " + "Expected 'cdap.<namespace>.system.queue.<app>.<flow>'" + "Received '%s'", queueTableName)); } return namespaceId; } /** * @param queueTableName actual queue table name * @return app name this queue belongs to */ public static String getApplicationName(String queueTableName) { // last three parts are namespaceId (optional - in which case it will be the default namespace), appName and flow String[] parts = queueTableName.split("\\."); return parts[parts.length - 2]; } /** * @param queueTableName actual queue table name * @return flow name this queue belongs to */ public static String getFlowName(String queueTableName) { // last three parts are namespaceId (optional - in which case it will be the default namespace), appName and flow String[] parts = queueTableName.split("\\."); return parts[parts.length - 1]; } /** * This determines the actual table name from the table name prefix and the name of the queue. * @param queueName The name of the queue. * @return the full name of the table that holds this queue. */ public String getActualTableName(QueueName queueName) { if (queueName.isQueue()) { // <root namespace>.<queue namespace>.system.queue.<app>.<flow> return getTableNameForFlow(queueName.getFirstComponent(), queueName.getSecondComponent(), queueName.getThirdComponent()); } else { throw new IllegalArgumentException("'" + queueName + "' is not a valid name for a queue."); } } protected String getTableNameForFlow(String namespaceId, String app, String flow) { String tablePrefix = getTableNamePrefix(namespaceId); String tableName = tablePrefix + "." + app + "." + flow; return HBaseTableUtil.getHBaseTableName(tableName); } public String getTableNamePrefix(String namespaceId) { // returns String with format: '<root namespace>.<namespaceId>.system.(stream|queue)' String tablePrefix = namespace.namespace(Id.DatasetInstance.from(namespaceId, unqualifiedTableNamePrefix)).getId(); return HBaseTableUtil.getHBaseTableName(tablePrefix); } }
address comments: use 'this.var' instead of just 'var''
cdap-data-fabric/src/main/java/co/cask/cdap/data2/transaction/queue/AbstractQueueAdmin.java
address comments: use 'this.var' instead of just 'var''
Java
apache-2.0
e138b1c1e5b8c53ed769868fdbccb3bf0e44f42b
0
nikita36078/J2ME-Loader,nikita36078/J2ME-Loader,nikita36078/J2ME-Loader,nikita36078/J2ME-Loader
/* * Copyright 2012 Kulikov Dmitriy * Copyright 2017-2018 Nikita Shakarun * * 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 javax.microedition.lcdui; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLUtils; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import androidx.annotation.NonNull; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.concurrent.TimeUnit; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import javax.microedition.lcdui.event.CanvasEvent; import javax.microedition.lcdui.event.Event; import javax.microedition.lcdui.event.EventFilter; import javax.microedition.lcdui.event.EventQueue; import javax.microedition.lcdui.graphics.CanvasView; import javax.microedition.lcdui.graphics.CanvasWrapper; import javax.microedition.lcdui.graphics.GlesView; import javax.microedition.lcdui.graphics.ShaderProgram; import javax.microedition.lcdui.keyboard.KeyMapper; import javax.microedition.lcdui.keyboard.VirtualKeyboard; import javax.microedition.lcdui.overlay.FpsCounter; import javax.microedition.lcdui.overlay.Overlay; import javax.microedition.lcdui.overlay.OverlayView; import javax.microedition.shell.MicroActivity; import javax.microedition.util.ContextHolder; import io.reactivex.Single; import io.reactivex.schedulers.Schedulers; import ru.playsoftware.j2meloader.R; import ru.playsoftware.j2meloader.config.ShaderInfo; import static android.opengl.GLES20.*; import static android.opengl.GLSurfaceView.RENDERMODE_WHEN_DIRTY; @SuppressWarnings({"WeakerAccess", "unused"}) public abstract class Canvas extends Displayable { private static final String TAG = Canvas.class.getName(); public static final int KEY_POUND = 35; public static final int KEY_STAR = 42; public static final int KEY_NUM0 = 48; public static final int KEY_NUM1 = 49; public static final int KEY_NUM2 = 50; public static final int KEY_NUM3 = 51; public static final int KEY_NUM4 = 52; public static final int KEY_NUM5 = 53; public static final int KEY_NUM6 = 54; public static final int KEY_NUM7 = 55; public static final int KEY_NUM8 = 56; public static final int KEY_NUM9 = 57; public static final int KEY_UP = -1; public static final int KEY_DOWN = -2; public static final int KEY_LEFT = -3; public static final int KEY_RIGHT = -4; public static final int KEY_FIRE = -5; public static final int KEY_SOFT_LEFT = -6; public static final int KEY_SOFT_RIGHT = -7; public static final int KEY_CLEAR = -8; public static final int KEY_SEND = -10; public static final int KEY_END = -11; public static final int UP = 1; public static final int LEFT = 2; public static final int RIGHT = 5; public static final int DOWN = 6; public static final int FIRE = 8; public static final int GAME_A = 9; public static final int GAME_B = 10; public static final int GAME_C = 11; public static final int GAME_D = 12; private static final float FULLSCREEN_HEIGHT_RATIO = 0.85f; private static boolean filter; private static boolean touchInput; private static int graphicsMode; private static ShaderInfo shaderFilter; private static boolean parallelRedraw; private static boolean forceFullscreen; private static boolean showFps; private static int backgroundColor; private static int scaleRatio; private static int fpsLimit; private final Object paintSync = new Object(); private final PaintEvent paintEvent = new PaintEvent(); protected int width, height; protected int maxHeight; private LinearLayout layout; private SurfaceView innerView; private Surface surface; private final CanvasWrapper canvasWrapper = new CanvasWrapper(filter); private GLRenderer renderer; private int displayWidth; private int displayHeight; private boolean fullscreen = forceFullscreen; private boolean visible; private boolean sizeChangedCalled; private Image offscreen; private Image offscreenCopy; private int onX, onY, onWidth, onHeight; private final RectF virtualScreen = new RectF(0, 0, displayWidth, displayHeight); private long lastFrameTime = System.currentTimeMillis(); private Handler uiHandler; private final Overlay overlay = ContextHolder.getVk(); private FpsCounter fpsCounter; private static int scaleType; private static int screenGravity; public Canvas() { if (graphicsMode == 1) { renderer = new GLRenderer(); } if (parallelRedraw) { uiHandler = new Handler(Looper.getMainLooper(), msg -> repaintScreen()); } displayWidth = ContextHolder.getDisplayWidth(); displayHeight = ContextHolder.getDisplayHeight(); updateSize(); } public static void setShaderFilter(ShaderInfo shader) { Canvas.shaderFilter = shader; } public static void setScale(int screenGravity, int scaleType, int scaleRatio) { Canvas.screenGravity = screenGravity; Canvas.scaleType = scaleType; Canvas.scaleRatio = scaleRatio; } public static void setBackgroundColor(int color) { backgroundColor = color | 0xFF000000; } public static void setFilterBitmap(boolean filter) { Canvas.filter = filter; } public static void setHasTouchInput(boolean touchInput) { Canvas.touchInput = touchInput; } public static void setGraphicsMode(int mode, boolean parallel) { Canvas.graphicsMode = mode; Canvas.parallelRedraw = (mode == 0 || mode == 3) && parallel; } public static void setForceFullscreen(boolean forceFullscreen) { Canvas.forceFullscreen = forceFullscreen; } public static void setShowFps(boolean showFps) { Canvas.showFps = showFps; } public static void setLimitFps(int fpsLimit) { if (fpsLimit == 0 && (graphicsMode == 1 || graphicsMode == 2)) { // hack for async redraw fpsLimit = 1000; } Canvas.fpsLimit = fpsLimit; } public int getKeyCode(int gameAction) { int res = KeyMapper.getKeyCode(gameAction); if (res != Integer.MAX_VALUE) { return res; } else { throw new IllegalArgumentException("unknown game action " + gameAction); } } public int getGameAction(int keyCode) { int res = KeyMapper.getGameAction(keyCode); if (res != Integer.MAX_VALUE) { return res; } else { throw new IllegalArgumentException("unknown keycode " + keyCode); } } public String getKeyName(int keyCode) { String res = KeyMapper.getKeyName(keyCode); if (res != null) { return res; } else { throw new IllegalArgumentException("unknown keycode " + keyCode); } } public void postKeyPressed(int keyCode) { Display.postEvent(CanvasEvent.getInstance(this, CanvasEvent.KEY_PRESSED, KeyMapper.convertKeyCode(keyCode))); } public void postKeyReleased(int keyCode) { Display.postEvent(CanvasEvent.getInstance(this, CanvasEvent.KEY_RELEASED, KeyMapper.convertKeyCode(keyCode))); } public void postKeyRepeated(int keyCode) { Display.postEvent(CanvasEvent.getInstance(this, CanvasEvent.KEY_REPEATED, KeyMapper.convertKeyCode(keyCode))); } public void callShowNotify() { visible = true; showNotify(); } public void callHideNotify() { hideNotify(); visible = false; } public void onDraw(android.graphics.Canvas canvas) { if (graphicsMode != 2) return; // Fix for Android Pie CanvasWrapper g = canvasWrapper; g.bind(canvas); g.clear(backgroundColor); offscreenCopy.getBitmap().prepareToDraw(); g.drawImage(offscreenCopy, virtualScreen); if (fpsCounter != null) { fpsCounter.increment(); } } public Single<Bitmap> getScreenShot() { if (renderer != null) { return renderer.takeScreenShot(); } return Single.create(emitter -> { Bitmap bitmap = Bitmap.createBitmap(onWidth, onHeight, Bitmap.Config.ARGB_8888); canvasWrapper.bind(new android.graphics.Canvas(bitmap)); canvasWrapper.drawImage(offscreenCopy, new RectF(0, 0, onWidth, onHeight)); emitter.onSuccess(bitmap); }); } private boolean checkSizeChanged() { int tmpWidth = width; int tmpHeight = height; updateSize(); return width != tmpWidth || height != tmpHeight; } /** * Update the size and position of the virtual screen relative to the real one. */ public void updateSize() { /* * We turn the sizes of the virtual screen into the sizes of the visible canvas. * * At the same time, we take into account that one or both virtual sizes can be less * than zero, which means auto-selection of this size so that the resulting canvas * has the same aspect ratio as the actual screen of the device. */ int scaledDisplayHeight; VirtualKeyboard vk = ContextHolder.getVk(); boolean isPhoneSkin = vk != null && vk.isPhone(); // if phone keyboard layout is active, then scale down the virtual screen if (isPhoneSkin) { scaledDisplayHeight = (int) (displayHeight - vk.getPhoneKeyboardHeight() - 1); } else { scaledDisplayHeight = displayHeight; } if (virtualWidth > 0) { if (virtualHeight > 0) { /* * the width and height of the canvas are strictly set */ width = virtualWidth; height = virtualHeight; } else { /* * only the canvas width is set * height is selected by the ratio of the real screen */ width = virtualWidth; height = scaledDisplayHeight * virtualWidth / displayWidth; } } else { if (virtualHeight > 0) { /* * only the canvas height is set * width is selected by the ratio of the real screen */ width = displayWidth * virtualHeight / scaledDisplayHeight; height = virtualHeight; } else { /* * nothing is set - screen-sized canvas */ width = displayWidth; height = scaledDisplayHeight; } } /* * calculate the maximum height */ maxHeight = height; /* * calculate the current height */ if (!fullscreen) { height = (int) (height * FULLSCREEN_HEIGHT_RATIO); } /* * We turn the size of the canvas into the size of the image * that will be displayed on the screen of the device. */ switch (scaleType) { case 0: // without scaling onWidth = width; onHeight = height; break; case 1: // try to fit in width onWidth = displayWidth; onHeight = height * displayWidth / width; if (onHeight > scaledDisplayHeight) { // if height is too big, then fit in height onHeight = scaledDisplayHeight; onWidth = width * scaledDisplayHeight / height; } break; case 2: // scaling without preserving the aspect ratio: // just stretch the picture to full screen onWidth = displayWidth; onHeight = scaledDisplayHeight; break; } onWidth = onWidth * scaleRatio / 100; onHeight = onHeight * scaleRatio / 100; int screenGravity = isPhoneSkin ? 1 : Canvas.screenGravity; switch (screenGravity) { case 0: // left onX = 0; onY = (displayHeight - onHeight) / 2; break; case 1: // top onX = (displayWidth - onWidth) / 2; onY = 0; break; case 2: // center onX = (displayWidth - onWidth) / 2; onY = (displayHeight - onHeight) / 2; break; case 3: // right onX = displayWidth - onWidth; onY = (displayHeight - onHeight) / 2; break; case 4: // bottom onX = (displayWidth - onWidth) / 2; onY = displayHeight - onHeight; break; } RectF screen = new RectF(0, 0, displayWidth, displayHeight); virtualScreen.set(onX, onY, onX + onWidth, onY + onHeight); if (offscreen == null) { offscreen = Image.createTransparentImage(width, maxHeight); offscreenCopy = Image.createTransparentImage(width, maxHeight); } if (offscreen.getWidth() != width || offscreen.getHeight() != height) { offscreen.setSize(width, height); offscreenCopy.setSize(width, height); } offscreen.getSingleGraphics().reset(); offscreenCopy.getSingleGraphics().reset(); if (overlay != null) { overlay.resize(screen, virtualScreen); } if (graphicsMode == 1) { float gl = 2.0f * virtualScreen.left / displayWidth - 1.0f; float gt = 1.0f - 2.0f * virtualScreen.top / displayHeight; float gr = 2.0f * virtualScreen.right / displayWidth - 1.0f; float gb = 1.0f - 2.0f * virtualScreen.bottom / displayHeight; float th = (float) height / offscreen.getBitmap().getHeight(); float tw = (float) width / offscreen.getBitmap().getWidth(); renderer.updateSize(gl, gt, gr, gb, th, tw); } } /** * Convert the screen coordinates of the pointer into the virtual ones. * * @param x the pointer coordinate on the real screen * @return the corresponding pointer coordinate on the virtual screen */ private float convertPointerX(float x) { return (x - onX) * width / onWidth; } /** * Convert the screen coordinates of the pointer into the virtual ones. * * @param y the pointer coordinate on the real screen * @return the corresponding pointer coordinate on the virtual screen */ private float convertPointerY(float y) { return (y - onY) * height / onHeight; } @SuppressLint("ClickableViewAccessibility") @Override public View getDisplayableView() { if (layout == null) { layout = (LinearLayout) super.getDisplayableView(); MicroActivity activity = getParentActivity(); if (graphicsMode == 1) { GlesView glesView = new GlesView(activity); glesView.setRenderer(renderer); glesView.setRenderMode(RENDERMODE_WHEN_DIRTY); renderer.setView(glesView); innerView = glesView; } else { CanvasView canvasView = new CanvasView(this, activity); if (graphicsMode == 2) { canvasView.setWillNotDraw(false); } canvasView.getHolder().setFormat(PixelFormat.RGBA_8888); innerView = canvasView; } ViewCallbacks callback = new ViewCallbacks(innerView); innerView.getHolder().addCallback(callback); innerView.setOnTouchListener(callback); innerView.setOnKeyListener(callback); innerView.setFocusableInTouchMode(true); layout.addView(innerView); innerView.requestFocus(); } return layout; } @Override public void clearDisplayableView() { synchronized (paintSync) { super.clearDisplayableView(); layout = null; innerView = null; } } public void setFullScreenMode(boolean flag) { synchronized (paintSync) { if (fullscreen != flag) { fullscreen = flag; updateSize(); Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.SIZE_CHANGED, width, height)); } } } public boolean hasPointerEvents() { return touchInput; } public boolean hasPointerMotionEvents() { return touchInput; } public boolean hasRepeatEvents() { return true; } public boolean isDoubleBuffered() { return true; } @Override public int getWidth() { return width; } @Override public int getHeight() { return height; } protected abstract void paint(Graphics g); public final void repaint() { repaint(0, 0, width, height); } public final void repaint(int x, int y, int width, int height) { limitFps(); Display.postEvent(paintEvent); } // GameCanvas public void flushBuffer(Image image, int x, int y, int width, int height) { limitFps(); synchronized (paintSync) { offscreenCopy.getSingleGraphics().flush(image, x, y, width, height); if (graphicsMode == 1) { if (innerView != null) { renderer.requestRender(); } return; } else if (graphicsMode == 2) { if (innerView != null) { innerView.postInvalidate(); } return; } if (!parallelRedraw) { repaintScreen(); } else if (!uiHandler.hasMessages(0)) { uiHandler.sendEmptyMessage(0); } } } // ExtendedImage public void flushBuffer(Image image, int x, int y) { limitFps(); synchronized (paintSync) { image.copyTo(offscreenCopy, x, y); if (graphicsMode == 1) { if (innerView != null) { renderer.requestRender(); } return; } else if (graphicsMode == 2) { if (innerView != null) { innerView.postInvalidate(); } return; } if (!parallelRedraw) { repaintScreen(); } else if (!uiHandler.hasMessages(0)) { uiHandler.sendEmptyMessage(0); } } } private void limitFps() { if (fpsLimit <= 0) return; try { long millis = (1000 / fpsLimit) - (System.currentTimeMillis() - lastFrameTime); if (millis > 0) Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } lastFrameTime = System.currentTimeMillis(); } @SuppressLint("NewApi") private boolean repaintScreen() { if (surface == null || !surface.isValid()) { return true; } try { android.graphics.Canvas canvas = graphicsMode == 3 ? surface.lockHardwareCanvas() : surface.lockCanvas(null); if (canvas == null) { return true; } CanvasWrapper g = this.canvasWrapper; g.bind(canvas); g.clear(backgroundColor); g.drawImage(offscreenCopy, virtualScreen); surface.unlockCanvasAndPost(canvas); if (fpsCounter != null) { fpsCounter.increment(); } if (parallelRedraw) uiHandler.removeMessages(0); } catch (Exception e) { Log.w(TAG, "repaintScreen: " + e); } return true; } /** * After calling this method, an immediate redraw is guaranteed to occur, * and the calling thread is blocked until it is completed. */ public final void serviceRepaints() { EventQueue queue = Display.getEventQueue(); /* * blocking order: * * 1 - queue.this * 2 - queue.queue * * accordingly, inside the EventQueue, the order must be the same, * otherwise mutual blocking of two threads is possible (everything will hang) */ //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (queue) { /* * This synchronization actually stops the events processing * just before changing the value of currentEvent() * * Then there are only two options: */ if (queue.currentEvent() == paintEvent) { /* * if repaint() is being processed there now, * then you just need to wait for it to finish */ if (Thread.holdsLock(paintSync)) { // Avoid deadlock return; } try { queue.wait(); } catch (InterruptedException ie) { ie.printStackTrace(); } } else if (queue.removeEvents(paintEvent)) { /* * if now something else is being processed there (not repaint), * but the repaint was in the queue (and was removed from there), * then it needs to be synchronously called from here */ paintEvent.run(); } } } protected void showNotify() { } protected void hideNotify() { } public void keyPressed(int keyCode) { } public void keyRepeated(int keyCode) { } public void keyReleased(int keyCode) { } public void pointerPressed(int pointer, float x, float y) { if (pointer == 0) { pointerPressed(Math.round(x), Math.round(y)); } } public void pointerDragged(int pointer, float x, float y) { if (pointer == 0) { pointerDragged(Math.round(x), Math.round(y)); } } public void pointerReleased(int pointer, float x, float y) { if (pointer == 0) { pointerReleased(Math.round(x), Math.round(y)); } } public void pointerPressed(int x, int y) { } public void pointerDragged(int x, int y) { } public void pointerReleased(int x, int y) { } void setInvisible() { this.visible = false; } private class GLRenderer implements GLSurfaceView.Renderer { private final FloatBuffer vbo = ByteBuffer.allocateDirect(8 * 2 * 4) .order(ByteOrder.nativeOrder()).asFloatBuffer(); private GLSurfaceView mView; private final int[] bgTextureId = new int[1]; private ShaderProgram program; private boolean isStarted; private Runnable screenshotTask; @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { program = new ShaderProgram(shaderFilter); int c = Canvas.backgroundColor; glClearColor((c >> 16 & 0xff) / 255.0f, (c >> 8 & 0xff) / 255.0f, (c & 0xff) / 255.0f, 1.0f); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDepthMask(false); initTex(); Bitmap bitmap = offscreenCopy.getBitmap(); program.loadVbo(vbo, bitmap.getWidth(), bitmap.getHeight()); if (shaderFilter != null && shaderFilter.values != null) { glUniform4fv(program.uSetting, 1, shaderFilter.values, 0); } isStarted = true; } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { glViewport(0, 0, width, height); glUniform2f(program.uPixelDelta, 1.0f / width, 1.0f / height); } @Override public void onDrawFrame(GL10 gl) { glClear(GL_COLOR_BUFFER_BIT); GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, offscreenCopy.getBitmap(), 0); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); if (fpsCounter != null) { fpsCounter.increment(); } if (screenshotTask != null) { screenshotTask.run(); screenshotTask = null; } } private void initTex() { glGenTextures(1, bgTextureId, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, bgTextureId[0]); glTexParameteri(GLES20.GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter ? GL_LINEAR : GL_NEAREST); glTexParameteri(GLES20.GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter ? GL_LINEAR : GL_NEAREST); glTexParameteri(GLES20.GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GLES20.GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // юнит текстуры glUniform1i(program.uTextureUnit, 0); } public void updateSize(float gl, float gt, float gr, float gb, float th, float tw) { synchronized (vbo) { FloatBuffer vertex_bg = vbo; vertex_bg.rewind(); vertex_bg.put(gl).put(gt).put(0.0f).put(0.0f);// lt vertex_bg.put(gl).put(gb).put(0.0f).put( th);// lb vertex_bg.put(gr).put(gt).put( tw).put(0.0f);// rt vertex_bg.put(gr).put(gb).put( tw).put( th);// rb } if (isStarted) { mView.queueEvent(() -> { Bitmap bitmap = offscreenCopy.getBitmap(); program.loadVbo(vbo, bitmap.getWidth(), bitmap.getHeight()); }); } } public void requestRender() { mView.requestRender(); } public void setView(GLSurfaceView mView) { this.mView = mView; } public void stop() { isStarted = false; mView.onPause(); } public void start() { mView.onResume(); } private Single<Bitmap> takeScreenShot() { return Single.<ByteBuffer>create(emitter -> { ByteBuffer buf = ByteBuffer.allocateDirect(onWidth * onHeight * 4).order(ByteOrder.nativeOrder()); screenshotTask = () -> { try { glReadPixels(displayWidth - onWidth - onX, displayHeight - onHeight - onY, onWidth, onHeight, GL_RGBA, GL_UNSIGNED_BYTE, buf); emitter.onSuccess(buf); } catch (Throwable e) { emitter.onError(e); } }; }).timeout(3, TimeUnit.SECONDS) .subscribeOn(Schedulers.computation()) .observeOn(Schedulers.computation()) .map(bb -> { Bitmap rawBitmap = Bitmap.createBitmap(onWidth, onHeight, Bitmap.Config.ARGB_8888); bb.rewind(); rawBitmap.copyPixelsFromBuffer(bb); Matrix m = new Matrix(); m.setScale(1.0f, -1.0f); return Bitmap.createBitmap(rawBitmap, 0, 0, onWidth, onHeight, m, false); }); } } private class PaintEvent extends Event implements EventFilter { private int enqueued = 0; @Override public void process() { synchronized (paintSync) { if (surface == null || !surface.isValid() || !visible) { return; } Graphics g = offscreen.getSingleGraphics(); g.reset(); try { paint(g); } catch (Throwable t) { t.printStackTrace(); } offscreen.copyTo(offscreenCopy); if (graphicsMode == 1) { if (innerView != null) { renderer.requestRender(); } } else if (graphicsMode == 2) { if (innerView != null) { innerView.postInvalidate(); } } else if (!parallelRedraw) { repaintScreen(); } else if (!uiHandler.hasMessages(0)) { uiHandler.sendEmptyMessage(0); } } } @Override public void recycle() { } @Override public void enterQueue() { enqueued++; } @Override public void leaveQueue() { enqueued--; } /** * The queue should contain no more than two repaint events * <p> * One won't be smooth enough, and if you add more than two, * then how to determine exactly how many of them need to be added? */ @Override public boolean placeableAfter(Event event) { return event != this; } @Override public boolean accept(Event event) { return event == this; } } private class ViewCallbacks implements View.OnTouchListener, SurfaceHolder.Callback, View.OnKeyListener { private final View mView; OverlayView overlayView; private final FrameLayout rootView; public ViewCallbacks(View view) { mView = view; rootView = ((Activity) view.getContext()).findViewById(R.id.midletFrame); overlayView = rootView.findViewById(R.id.vOverlay); } @Override public boolean onKey(View v, int keyCode, KeyEvent event) { switch (event.getAction()) { case KeyEvent.ACTION_DOWN: return onKeyDown(keyCode, event); case KeyEvent.ACTION_UP: return onKeyUp(keyCode, event); case KeyEvent.ACTION_MULTIPLE: if (keyCode == KeyEvent.KEYCODE_UNKNOWN) { String characters = event.getCharacters(); for (int i = 0; i < characters.length(); i++) { int cp = characters.codePointAt(i); postKeyPressed(cp); postKeyReleased(cp); } return true; } else { return onKeyDown(keyCode, event); } } return false; } public boolean onKeyDown(int keyCode, KeyEvent event) { keyCode = KeyMapper.convertAndroidKeyCode(keyCode, event); if (keyCode == 0) { return false; } if (event.getRepeatCount() == 0) { if (overlay == null || !overlay.keyPressed(keyCode)) { postKeyPressed(keyCode); } } else { if (overlay == null || !overlay.keyRepeated(keyCode)) { postKeyRepeated(keyCode); } } return true; } public boolean onKeyUp(int keyCode, KeyEvent event) { int midpKeyCode = KeyMapper.convertAndroidKeyCode(keyCode, event); if (midpKeyCode == 0) { return false; } long pressedTime = event.getEventTime() - event.getDownTime(); if (pressedTime < 100) { mView.postDelayed(() -> { if (overlay == null || !overlay.keyReleased(midpKeyCode)) { postKeyReleased(midpKeyCode); } }, 100 - pressedTime); } else { if (overlay == null || !overlay.keyReleased(midpKeyCode)) { postKeyReleased(midpKeyCode); } } return true; } @Override @SuppressLint("ClickableViewAccessibility") public boolean onTouch(View v, MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: if (overlay != null) { overlay.show(); } case MotionEvent.ACTION_POINTER_DOWN: int index = event.getActionIndex(); int id = event.getPointerId(index); float x = event.getX(index); float y = event.getY(index); if (overlay != null) { overlay.pointerPressed(id, x, y); } if (touchInput && id == 0 && virtualScreen.contains(x, y)) { Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.POINTER_PRESSED, id, convertPointerX(x), convertPointerY(y))); } break; case MotionEvent.ACTION_MOVE: int pointerCount = event.getPointerCount(); int historySize = event.getHistorySize(); for (int h = 0; h < historySize; h++) { for (int p = 0; p < pointerCount; p++) { id = event.getPointerId(p); x = event.getHistoricalX(p, h); y = event.getHistoricalY(p, h); if (overlay != null) { overlay.pointerDragged(id, x, y); } if (touchInput && id == 0 && virtualScreen.contains(x, y)) { Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.POINTER_DRAGGED, id, convertPointerX(x), convertPointerY(y))); } } } for (int p = 0; p < pointerCount; p++) { id = event.getPointerId(p); x = event.getX(p); y = event.getY(p); if (overlay != null) { overlay.pointerDragged(id, x, y); } if (touchInput && id == 0 && virtualScreen.contains(x, y)) { Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.POINTER_DRAGGED, id, convertPointerX(x), convertPointerY(y))); } } break; case MotionEvent.ACTION_UP: if (overlay != null) { overlay.hide(); } case MotionEvent.ACTION_POINTER_UP: index = event.getActionIndex(); id = event.getPointerId(index); x = event.getX(index); y = event.getY(index); if (overlay != null) { overlay.pointerReleased(id, x, y); } if (touchInput && id == 0 && virtualScreen.contains(x, y)) { Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.POINTER_RELEASED, id, convertPointerX(x), convertPointerY(y))); } break; case MotionEvent.ACTION_CANCEL: if (overlay != null) { overlay.cancel(); } break; default: return false; } return true; } @Override public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int newWidth, int newHeight) { Rect offsetViewBounds = new Rect(0, 0, newWidth, newHeight); // calculates the relative coordinates to the parent rootView.offsetDescendantRectToMyCoords(mView, offsetViewBounds); synchronized (paintSync) { overlayView.setTargetBounds(offsetViewBounds); displayWidth = newWidth; displayHeight = newHeight; if (checkSizeChanged() || !sizeChangedCalled) { Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.SIZE_CHANGED, width, height)); sizeChangedCalled = true; } } Display.postEvent(paintEvent); } @Override public void surfaceCreated(@NonNull SurfaceHolder holder) { if (renderer != null) { renderer.start(); } synchronized (paintSync) { surface = holder.getSurface(); Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.SHOW_NOTIFY)); } if (showFps) { fpsCounter = new FpsCounter(overlayView); overlayView.addLayer(fpsCounter); } overlayView.setVisibility(true); if (overlay != null) { overlay.setTarget(Canvas.this); } } @Override public void surfaceDestroyed(@NonNull SurfaceHolder holder) { if (renderer != null) { renderer.stop(); } synchronized (paintSync) { surface = null; Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.HIDE_NOTIFY)); if (fpsCounter != null) { fpsCounter.stop(); overlayView.removeLayer(fpsCounter); fpsCounter = null; } } overlayView.setVisibility(false); if (overlay != null) { overlay.setTarget(null); overlay.cancel(); } } } }
app/src/main/java/javax/microedition/lcdui/Canvas.java
/* * Copyright 2012 Kulikov Dmitriy * Copyright 2017-2018 Nikita Shakarun * * 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 javax.microedition.lcdui; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLUtils; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import androidx.annotation.NonNull; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.concurrent.TimeUnit; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import javax.microedition.lcdui.event.CanvasEvent; import javax.microedition.lcdui.event.Event; import javax.microedition.lcdui.event.EventFilter; import javax.microedition.lcdui.event.EventQueue; import javax.microedition.lcdui.graphics.CanvasView; import javax.microedition.lcdui.graphics.CanvasWrapper; import javax.microedition.lcdui.graphics.GlesView; import javax.microedition.lcdui.graphics.ShaderProgram; import javax.microedition.lcdui.keyboard.KeyMapper; import javax.microedition.lcdui.keyboard.VirtualKeyboard; import javax.microedition.lcdui.overlay.FpsCounter; import javax.microedition.lcdui.overlay.Overlay; import javax.microedition.lcdui.overlay.OverlayView; import javax.microedition.shell.MicroActivity; import javax.microedition.util.ContextHolder; import io.reactivex.Single; import io.reactivex.schedulers.Schedulers; import ru.playsoftware.j2meloader.R; import ru.playsoftware.j2meloader.config.ShaderInfo; import static android.opengl.GLES20.*; import static android.opengl.GLSurfaceView.RENDERMODE_WHEN_DIRTY; @SuppressWarnings({"WeakerAccess", "unused"}) public abstract class Canvas extends Displayable { private static final String TAG = Canvas.class.getName(); public static final int KEY_POUND = 35; public static final int KEY_STAR = 42; public static final int KEY_NUM0 = 48; public static final int KEY_NUM1 = 49; public static final int KEY_NUM2 = 50; public static final int KEY_NUM3 = 51; public static final int KEY_NUM4 = 52; public static final int KEY_NUM5 = 53; public static final int KEY_NUM6 = 54; public static final int KEY_NUM7 = 55; public static final int KEY_NUM8 = 56; public static final int KEY_NUM9 = 57; public static final int KEY_UP = -1; public static final int KEY_DOWN = -2; public static final int KEY_LEFT = -3; public static final int KEY_RIGHT = -4; public static final int KEY_FIRE = -5; public static final int KEY_SOFT_LEFT = -6; public static final int KEY_SOFT_RIGHT = -7; public static final int KEY_CLEAR = -8; public static final int KEY_SEND = -10; public static final int KEY_END = -11; public static final int UP = 1; public static final int LEFT = 2; public static final int RIGHT = 5; public static final int DOWN = 6; public static final int FIRE = 8; public static final int GAME_A = 9; public static final int GAME_B = 10; public static final int GAME_C = 11; public static final int GAME_D = 12; private static final float FULLSCREEN_HEIGHT_RATIO = 0.85f; private static boolean filter; private static boolean touchInput; private static int graphicsMode; private static ShaderInfo shaderFilter; private static boolean parallelRedraw; private static boolean forceFullscreen; private static boolean showFps; private static int backgroundColor; private static int scaleRatio; private static int fpsLimit; private final Object paintSync = new Object(); private final PaintEvent paintEvent = new PaintEvent(); protected int width, height; protected int maxHeight; private LinearLayout layout; private SurfaceView innerView; private Surface surface; private final CanvasWrapper canvasWrapper = new CanvasWrapper(filter); private GLRenderer renderer; private int displayWidth; private int displayHeight; private boolean fullscreen = forceFullscreen; private boolean visible; private boolean sizeChangedCalled; private Image offscreen; private Image offscreenCopy; private int onX, onY, onWidth, onHeight; private final RectF virtualScreen = new RectF(0, 0, displayWidth, displayHeight); private long lastFrameTime = System.currentTimeMillis(); private Handler uiHandler; private final Overlay overlay = ContextHolder.getVk(); private FpsCounter fpsCounter; private static int scaleType; private static int screenGravity; public Canvas() { if (graphicsMode == 1) { renderer = new GLRenderer(); } if (parallelRedraw) { uiHandler = new Handler(Looper.getMainLooper(), msg -> repaintScreen()); } displayWidth = ContextHolder.getDisplayWidth(); displayHeight = ContextHolder.getDisplayHeight(); updateSize(); } public static void setShaderFilter(ShaderInfo shader) { Canvas.shaderFilter = shader; } public static void setScale(int screenGravity, int scaleType, int scaleRatio) { Canvas.screenGravity = screenGravity; Canvas.scaleType = scaleType; Canvas.scaleRatio = scaleRatio; } public static void setBackgroundColor(int color) { backgroundColor = color | 0xFF000000; } public static void setFilterBitmap(boolean filter) { Canvas.filter = filter; } public static void setHasTouchInput(boolean touchInput) { Canvas.touchInput = touchInput; } public static void setGraphicsMode(int mode, boolean parallel) { Canvas.graphicsMode = mode; Canvas.parallelRedraw = (mode == 0 || mode == 3) && parallel; } public static void setForceFullscreen(boolean forceFullscreen) { Canvas.forceFullscreen = forceFullscreen; } public static void setShowFps(boolean showFps) { Canvas.showFps = showFps; } public static void setLimitFps(int fpsLimit) { Canvas.fpsLimit = fpsLimit; } public int getKeyCode(int gameAction) { int res = KeyMapper.getKeyCode(gameAction); if (res != Integer.MAX_VALUE) { return res; } else { throw new IllegalArgumentException("unknown game action " + gameAction); } } public int getGameAction(int keyCode) { int res = KeyMapper.getGameAction(keyCode); if (res != Integer.MAX_VALUE) { return res; } else { throw new IllegalArgumentException("unknown keycode " + keyCode); } } public String getKeyName(int keyCode) { String res = KeyMapper.getKeyName(keyCode); if (res != null) { return res; } else { throw new IllegalArgumentException("unknown keycode " + keyCode); } } public void postKeyPressed(int keyCode) { Display.postEvent(CanvasEvent.getInstance(this, CanvasEvent.KEY_PRESSED, KeyMapper.convertKeyCode(keyCode))); } public void postKeyReleased(int keyCode) { Display.postEvent(CanvasEvent.getInstance(this, CanvasEvent.KEY_RELEASED, KeyMapper.convertKeyCode(keyCode))); } public void postKeyRepeated(int keyCode) { Display.postEvent(CanvasEvent.getInstance(this, CanvasEvent.KEY_REPEATED, KeyMapper.convertKeyCode(keyCode))); } public void callShowNotify() { visible = true; showNotify(); } public void callHideNotify() { hideNotify(); visible = false; } public void onDraw(android.graphics.Canvas canvas) { if (graphicsMode != 2) return; // Fix for Android Pie CanvasWrapper g = canvasWrapper; g.bind(canvas); g.clear(backgroundColor); offscreenCopy.getBitmap().prepareToDraw(); g.drawImage(offscreenCopy, virtualScreen); if (fpsCounter != null) { fpsCounter.increment(); } } public Single<Bitmap> getScreenShot() { if (renderer != null) { return renderer.takeScreenShot(); } return Single.create(emitter -> { Bitmap bitmap = Bitmap.createBitmap(onWidth, onHeight, Bitmap.Config.ARGB_8888); canvasWrapper.bind(new android.graphics.Canvas(bitmap)); canvasWrapper.drawImage(offscreenCopy, new RectF(0, 0, onWidth, onHeight)); emitter.onSuccess(bitmap); }); } private boolean checkSizeChanged() { int tmpWidth = width; int tmpHeight = height; updateSize(); return width != tmpWidth || height != tmpHeight; } /** * Update the size and position of the virtual screen relative to the real one. */ public void updateSize() { /* * We turn the sizes of the virtual screen into the sizes of the visible canvas. * * At the same time, we take into account that one or both virtual sizes can be less * than zero, which means auto-selection of this size so that the resulting canvas * has the same aspect ratio as the actual screen of the device. */ int scaledDisplayHeight; VirtualKeyboard vk = ContextHolder.getVk(); boolean isPhoneSkin = vk != null && vk.isPhone(); // if phone keyboard layout is active, then scale down the virtual screen if (isPhoneSkin) { scaledDisplayHeight = (int) (displayHeight - vk.getPhoneKeyboardHeight() - 1); } else { scaledDisplayHeight = displayHeight; } if (virtualWidth > 0) { if (virtualHeight > 0) { /* * the width and height of the canvas are strictly set */ width = virtualWidth; height = virtualHeight; } else { /* * only the canvas width is set * height is selected by the ratio of the real screen */ width = virtualWidth; height = scaledDisplayHeight * virtualWidth / displayWidth; } } else { if (virtualHeight > 0) { /* * only the canvas height is set * width is selected by the ratio of the real screen */ width = displayWidth * virtualHeight / scaledDisplayHeight; height = virtualHeight; } else { /* * nothing is set - screen-sized canvas */ width = displayWidth; height = scaledDisplayHeight; } } /* * calculate the maximum height */ maxHeight = height; /* * calculate the current height */ if (!fullscreen) { height = (int) (height * FULLSCREEN_HEIGHT_RATIO); } /* * We turn the size of the canvas into the size of the image * that will be displayed on the screen of the device. */ switch (scaleType) { case 0: // without scaling onWidth = width; onHeight = height; break; case 1: // try to fit in width onWidth = displayWidth; onHeight = height * displayWidth / width; if (onHeight > scaledDisplayHeight) { // if height is too big, then fit in height onHeight = scaledDisplayHeight; onWidth = width * scaledDisplayHeight / height; } break; case 2: // scaling without preserving the aspect ratio: // just stretch the picture to full screen onWidth = displayWidth; onHeight = scaledDisplayHeight; break; } onWidth = onWidth * scaleRatio / 100; onHeight = onHeight * scaleRatio / 100; int screenGravity = isPhoneSkin ? 1 : Canvas.screenGravity; switch (screenGravity) { case 0: // left onX = 0; onY = (displayHeight - onHeight) / 2; break; case 1: // top onX = (displayWidth - onWidth) / 2; onY = 0; break; case 2: // center onX = (displayWidth - onWidth) / 2; onY = (displayHeight - onHeight) / 2; break; case 3: // right onX = displayWidth - onWidth; onY = (displayHeight - onHeight) / 2; break; case 4: // bottom onX = (displayWidth - onWidth) / 2; onY = displayHeight - onHeight; break; } RectF screen = new RectF(0, 0, displayWidth, displayHeight); virtualScreen.set(onX, onY, onX + onWidth, onY + onHeight); if (offscreen == null) { offscreen = Image.createTransparentImage(width, maxHeight); offscreenCopy = Image.createTransparentImage(width, maxHeight); } if (offscreen.getWidth() != width || offscreen.getHeight() != height) { offscreen.setSize(width, height); offscreenCopy.setSize(width, height); } offscreen.getSingleGraphics().reset(); offscreenCopy.getSingleGraphics().reset(); if (overlay != null) { overlay.resize(screen, virtualScreen); } if (graphicsMode == 1) { float gl = 2.0f * virtualScreen.left / displayWidth - 1.0f; float gt = 1.0f - 2.0f * virtualScreen.top / displayHeight; float gr = 2.0f * virtualScreen.right / displayWidth - 1.0f; float gb = 1.0f - 2.0f * virtualScreen.bottom / displayHeight; float th = (float) height / offscreen.getBitmap().getHeight(); float tw = (float) width / offscreen.getBitmap().getWidth(); renderer.updateSize(gl, gt, gr, gb, th, tw); } } /** * Convert the screen coordinates of the pointer into the virtual ones. * * @param x the pointer coordinate on the real screen * @return the corresponding pointer coordinate on the virtual screen */ private float convertPointerX(float x) { return (x - onX) * width / onWidth; } /** * Convert the screen coordinates of the pointer into the virtual ones. * * @param y the pointer coordinate on the real screen * @return the corresponding pointer coordinate on the virtual screen */ private float convertPointerY(float y) { return (y - onY) * height / onHeight; } @SuppressLint("ClickableViewAccessibility") @Override public View getDisplayableView() { if (layout == null) { layout = (LinearLayout) super.getDisplayableView(); MicroActivity activity = getParentActivity(); if (graphicsMode == 1) { GlesView glesView = new GlesView(activity); glesView.setRenderer(renderer); glesView.setRenderMode(RENDERMODE_WHEN_DIRTY); renderer.setView(glesView); innerView = glesView; } else { CanvasView canvasView = new CanvasView(this, activity); if (graphicsMode == 2) { canvasView.setWillNotDraw(false); } canvasView.getHolder().setFormat(PixelFormat.RGBA_8888); innerView = canvasView; } ViewCallbacks callback = new ViewCallbacks(innerView); innerView.getHolder().addCallback(callback); innerView.setOnTouchListener(callback); innerView.setOnKeyListener(callback); innerView.setFocusableInTouchMode(true); layout.addView(innerView); innerView.requestFocus(); } return layout; } @Override public void clearDisplayableView() { synchronized (paintSync) { super.clearDisplayableView(); layout = null; innerView = null; } } public void setFullScreenMode(boolean flag) { synchronized (paintSync) { if (fullscreen != flag) { fullscreen = flag; updateSize(); Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.SIZE_CHANGED, width, height)); } } } public boolean hasPointerEvents() { return touchInput; } public boolean hasPointerMotionEvents() { return touchInput; } public boolean hasRepeatEvents() { return true; } public boolean isDoubleBuffered() { return true; } @Override public int getWidth() { return width; } @Override public int getHeight() { return height; } protected abstract void paint(Graphics g); public final void repaint() { repaint(0, 0, width, height); } public final void repaint(int x, int y, int width, int height) { limitFps(); Display.postEvent(paintEvent); } // GameCanvas public void flushBuffer(Image image, int x, int y, int width, int height) { limitFps(); synchronized (paintSync) { offscreenCopy.getSingleGraphics().flush(image, x, y, width, height); if (graphicsMode == 1) { if (innerView != null) { renderer.requestRender(); } return; } else if (graphicsMode == 2) { if (innerView != null) { innerView.postInvalidate(); } return; } if (!parallelRedraw) { repaintScreen(); } else if (!uiHandler.hasMessages(0)) { uiHandler.sendEmptyMessage(0); } } } // ExtendedImage public void flushBuffer(Image image, int x, int y) { limitFps(); synchronized (paintSync) { image.copyTo(offscreenCopy, x, y); if (graphicsMode == 1) { if (innerView != null) { renderer.requestRender(); } return; } else if (graphicsMode == 2) { if (innerView != null) { innerView.postInvalidate(); } return; } if (!parallelRedraw) { repaintScreen(); } else if (!uiHandler.hasMessages(0)) { uiHandler.sendEmptyMessage(0); } } } private void limitFps() { if (fpsLimit <= 0) return; try { long millis = (1000 / fpsLimit) - (System.currentTimeMillis() - lastFrameTime); if (millis > 0) Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } lastFrameTime = System.currentTimeMillis(); } @SuppressLint("NewApi") private boolean repaintScreen() { if (surface == null || !surface.isValid()) { return true; } try { android.graphics.Canvas canvas = graphicsMode == 3 ? surface.lockHardwareCanvas() : surface.lockCanvas(null); if (canvas == null) { return true; } CanvasWrapper g = this.canvasWrapper; g.bind(canvas); g.clear(backgroundColor); g.drawImage(offscreenCopy, virtualScreen); surface.unlockCanvasAndPost(canvas); if (fpsCounter != null) { fpsCounter.increment(); } if (parallelRedraw) uiHandler.removeMessages(0); } catch (Exception e) { Log.w(TAG, "repaintScreen: " + e); } return true; } /** * After calling this method, an immediate redraw is guaranteed to occur, * and the calling thread is blocked until it is completed. */ public final void serviceRepaints() { EventQueue queue = Display.getEventQueue(); /* * blocking order: * * 1 - queue.this * 2 - queue.queue * * accordingly, inside the EventQueue, the order must be the same, * otherwise mutual blocking of two threads is possible (everything will hang) */ //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (queue) { /* * This synchronization actually stops the events processing * just before changing the value of currentEvent() * * Then there are only two options: */ if (queue.currentEvent() == paintEvent) { /* * if repaint() is being processed there now, * then you just need to wait for it to finish */ if (Thread.holdsLock(paintSync)) { // Avoid deadlock return; } try { queue.wait(); } catch (InterruptedException ie) { ie.printStackTrace(); } } else if (queue.removeEvents(paintEvent)) { /* * if now something else is being processed there (not repaint), * but the repaint was in the queue (and was removed from there), * then it needs to be synchronously called from here */ paintEvent.run(); } } } protected void showNotify() { } protected void hideNotify() { } public void keyPressed(int keyCode) { } public void keyRepeated(int keyCode) { } public void keyReleased(int keyCode) { } public void pointerPressed(int pointer, float x, float y) { if (pointer == 0) { pointerPressed(Math.round(x), Math.round(y)); } } public void pointerDragged(int pointer, float x, float y) { if (pointer == 0) { pointerDragged(Math.round(x), Math.round(y)); } } public void pointerReleased(int pointer, float x, float y) { if (pointer == 0) { pointerReleased(Math.round(x), Math.round(y)); } } public void pointerPressed(int x, int y) { } public void pointerDragged(int x, int y) { } public void pointerReleased(int x, int y) { } void setInvisible() { this.visible = false; } private class GLRenderer implements GLSurfaceView.Renderer { private final FloatBuffer vbo = ByteBuffer.allocateDirect(8 * 2 * 4) .order(ByteOrder.nativeOrder()).asFloatBuffer(); private GLSurfaceView mView; private final int[] bgTextureId = new int[1]; private ShaderProgram program; private boolean isStarted; private Runnable screenshotTask; @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { program = new ShaderProgram(shaderFilter); int c = Canvas.backgroundColor; glClearColor((c >> 16 & 0xff) / 255.0f, (c >> 8 & 0xff) / 255.0f, (c & 0xff) / 255.0f, 1.0f); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDepthMask(false); initTex(); Bitmap bitmap = offscreenCopy.getBitmap(); program.loadVbo(vbo, bitmap.getWidth(), bitmap.getHeight()); if (shaderFilter != null && shaderFilter.values != null) { glUniform4fv(program.uSetting, 1, shaderFilter.values, 0); } isStarted = true; } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { glViewport(0, 0, width, height); glUniform2f(program.uPixelDelta, 1.0f / width, 1.0f / height); } @Override public void onDrawFrame(GL10 gl) { glClear(GL_COLOR_BUFFER_BIT); GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, offscreenCopy.getBitmap(), 0); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); if (fpsCounter != null) { fpsCounter.increment(); } if (screenshotTask != null) { screenshotTask.run(); screenshotTask = null; } } private void initTex() { glGenTextures(1, bgTextureId, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, bgTextureId[0]); glTexParameteri(GLES20.GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter ? GL_LINEAR : GL_NEAREST); glTexParameteri(GLES20.GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter ? GL_LINEAR : GL_NEAREST); glTexParameteri(GLES20.GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GLES20.GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // юнит текстуры glUniform1i(program.uTextureUnit, 0); } public void updateSize(float gl, float gt, float gr, float gb, float th, float tw) { synchronized (vbo) { FloatBuffer vertex_bg = vbo; vertex_bg.rewind(); vertex_bg.put(gl).put(gt).put(0.0f).put(0.0f);// lt vertex_bg.put(gl).put(gb).put(0.0f).put( th);// lb vertex_bg.put(gr).put(gt).put( tw).put(0.0f);// rt vertex_bg.put(gr).put(gb).put( tw).put( th);// rb } if (isStarted) { mView.queueEvent(() -> { Bitmap bitmap = offscreenCopy.getBitmap(); program.loadVbo(vbo, bitmap.getWidth(), bitmap.getHeight()); }); } } public void requestRender() { mView.requestRender(); } public void setView(GLSurfaceView mView) { this.mView = mView; } public void stop() { isStarted = false; mView.onPause(); } public void start() { mView.onResume(); } private Single<Bitmap> takeScreenShot() { return Single.<ByteBuffer>create(emitter -> { ByteBuffer buf = ByteBuffer.allocateDirect(onWidth * onHeight * 4).order(ByteOrder.nativeOrder()); screenshotTask = () -> { try { glReadPixels(displayWidth - onWidth - onX, displayHeight - onHeight - onY, onWidth, onHeight, GL_RGBA, GL_UNSIGNED_BYTE, buf); emitter.onSuccess(buf); } catch (Throwable e) { emitter.onError(e); } }; }).timeout(3, TimeUnit.SECONDS) .subscribeOn(Schedulers.computation()) .observeOn(Schedulers.computation()) .map(bb -> { Bitmap rawBitmap = Bitmap.createBitmap(onWidth, onHeight, Bitmap.Config.ARGB_8888); bb.rewind(); rawBitmap.copyPixelsFromBuffer(bb); Matrix m = new Matrix(); m.setScale(1.0f, -1.0f); return Bitmap.createBitmap(rawBitmap, 0, 0, onWidth, onHeight, m, false); }); } } private class PaintEvent extends Event implements EventFilter { private int enqueued = 0; @Override public void process() { synchronized (paintSync) { if (surface == null || !surface.isValid() || !visible) { return; } Graphics g = offscreen.getSingleGraphics(); g.reset(); try { paint(g); } catch (Throwable t) { t.printStackTrace(); } offscreen.copyTo(offscreenCopy); if (graphicsMode == 1) { if (innerView != null) { renderer.requestRender(); } } else if (graphicsMode == 2) { if (innerView != null) { innerView.postInvalidate(); } } else if (!parallelRedraw) { repaintScreen(); } else if (!uiHandler.hasMessages(0)) { uiHandler.sendEmptyMessage(0); } } } @Override public void recycle() { } @Override public void enterQueue() { enqueued++; } @Override public void leaveQueue() { enqueued--; } /** * The queue should contain no more than two repaint events * <p> * One won't be smooth enough, and if you add more than two, * then how to determine exactly how many of them need to be added? */ @Override public boolean placeableAfter(Event event) { return event != this; } @Override public boolean accept(Event event) { return event == this; } } private class ViewCallbacks implements View.OnTouchListener, SurfaceHolder.Callback, View.OnKeyListener { private final View mView; OverlayView overlayView; private final FrameLayout rootView; public ViewCallbacks(View view) { mView = view; rootView = ((Activity) view.getContext()).findViewById(R.id.midletFrame); overlayView = rootView.findViewById(R.id.vOverlay); } @Override public boolean onKey(View v, int keyCode, KeyEvent event) { switch (event.getAction()) { case KeyEvent.ACTION_DOWN: return onKeyDown(keyCode, event); case KeyEvent.ACTION_UP: return onKeyUp(keyCode, event); case KeyEvent.ACTION_MULTIPLE: if (keyCode == KeyEvent.KEYCODE_UNKNOWN) { String characters = event.getCharacters(); for (int i = 0; i < characters.length(); i++) { int cp = characters.codePointAt(i); postKeyPressed(cp); postKeyReleased(cp); } return true; } else { return onKeyDown(keyCode, event); } } return false; } public boolean onKeyDown(int keyCode, KeyEvent event) { keyCode = KeyMapper.convertAndroidKeyCode(keyCode, event); if (keyCode == 0) { return false; } if (event.getRepeatCount() == 0) { if (overlay == null || !overlay.keyPressed(keyCode)) { postKeyPressed(keyCode); } } else { if (overlay == null || !overlay.keyRepeated(keyCode)) { postKeyRepeated(keyCode); } } return true; } public boolean onKeyUp(int keyCode, KeyEvent event) { int midpKeyCode = KeyMapper.convertAndroidKeyCode(keyCode, event); if (midpKeyCode == 0) { return false; } long pressedTime = event.getEventTime() - event.getDownTime(); if (pressedTime < 100) { mView.postDelayed(() -> { if (overlay == null || !overlay.keyReleased(midpKeyCode)) { postKeyReleased(midpKeyCode); } }, 100 - pressedTime); } else { if (overlay == null || !overlay.keyReleased(midpKeyCode)) { postKeyReleased(midpKeyCode); } } return true; } @Override @SuppressLint("ClickableViewAccessibility") public boolean onTouch(View v, MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: if (overlay != null) { overlay.show(); } case MotionEvent.ACTION_POINTER_DOWN: int index = event.getActionIndex(); int id = event.getPointerId(index); float x = event.getX(index); float y = event.getY(index); if (overlay != null) { overlay.pointerPressed(id, x, y); } if (touchInput && id == 0 && virtualScreen.contains(x, y)) { Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.POINTER_PRESSED, id, convertPointerX(x), convertPointerY(y))); } break; case MotionEvent.ACTION_MOVE: int pointerCount = event.getPointerCount(); int historySize = event.getHistorySize(); for (int h = 0; h < historySize; h++) { for (int p = 0; p < pointerCount; p++) { id = event.getPointerId(p); x = event.getHistoricalX(p, h); y = event.getHistoricalY(p, h); if (overlay != null) { overlay.pointerDragged(id, x, y); } if (touchInput && id == 0 && virtualScreen.contains(x, y)) { Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.POINTER_DRAGGED, id, convertPointerX(x), convertPointerY(y))); } } } for (int p = 0; p < pointerCount; p++) { id = event.getPointerId(p); x = event.getX(p); y = event.getY(p); if (overlay != null) { overlay.pointerDragged(id, x, y); } if (touchInput && id == 0 && virtualScreen.contains(x, y)) { Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.POINTER_DRAGGED, id, convertPointerX(x), convertPointerY(y))); } } break; case MotionEvent.ACTION_UP: if (overlay != null) { overlay.hide(); } case MotionEvent.ACTION_POINTER_UP: index = event.getActionIndex(); id = event.getPointerId(index); x = event.getX(index); y = event.getY(index); if (overlay != null) { overlay.pointerReleased(id, x, y); } if (touchInput && id == 0 && virtualScreen.contains(x, y)) { Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.POINTER_RELEASED, id, convertPointerX(x), convertPointerY(y))); } break; case MotionEvent.ACTION_CANCEL: if (overlay != null) { overlay.cancel(); } break; default: return false; } return true; } @Override public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int newWidth, int newHeight) { Rect offsetViewBounds = new Rect(0, 0, newWidth, newHeight); // calculates the relative coordinates to the parent rootView.offsetDescendantRectToMyCoords(mView, offsetViewBounds); synchronized (paintSync) { overlayView.setTargetBounds(offsetViewBounds); displayWidth = newWidth; displayHeight = newHeight; if (checkSizeChanged() || !sizeChangedCalled) { Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.SIZE_CHANGED, width, height)); sizeChangedCalled = true; } } Display.postEvent(paintEvent); } @Override public void surfaceCreated(@NonNull SurfaceHolder holder) { if (renderer != null) { renderer.start(); } synchronized (paintSync) { surface = holder.getSurface(); Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.SHOW_NOTIFY)); } if (showFps) { fpsCounter = new FpsCounter(overlayView); overlayView.addLayer(fpsCounter); } overlayView.setVisibility(true); if (overlay != null) { overlay.setTarget(Canvas.this); } } @Override public void surfaceDestroyed(@NonNull SurfaceHolder holder) { if (renderer != null) { renderer.stop(); } synchronized (paintSync) { surface = null; Display.postEvent(CanvasEvent.getInstance(Canvas.this, CanvasEvent.HIDE_NOTIFY)); if (fpsCounter != null) { fpsCounter.stop(); overlayView.removeLayer(fpsCounter); fpsCounter = null; } } overlayView.setVisibility(false); if (overlay != null) { overlay.setTarget(null); overlay.cancel(); } } } }
Add hack for async redraw
app/src/main/java/javax/microedition/lcdui/Canvas.java
Add hack for async redraw
Java
apache-2.0
6a4265b35e515799c52050fa7af095b1f829ca69
0
zibhub/GNDMS,zibhub/GNDMS,zibhub/GNDMS,zibhub/GNDMS
package de.zib.gndms.kit.network; /* * Copyright 2008-2011 Zuse Institute Berlin (ZIB) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import de.zib.gndms.stuff.threading.QueuedExecutor; import de.zib.gndms.kit.access.CredentialProvider; import org.apache.log4j.Logger; import org.globus.ftp.GridFTPClient; import org.globus.ftp.exception.ServerException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.*; /** * @author try ma ik jo rr a zib * * @version $Id$ * <p/> * User: mjorra, Date: 20.02.2009, Time: 17:37:59 */ public class NonblockingClientFactory extends AbstractGridFTPClientFactory{ private static final Logger log = Logger.getLogger( NonblockingClientFactory.class ); private int timeout = 20; private final TimeUnit unit = TimeUnit.SECONDS; private long delay = 500; // in ms private final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool( 1 ); private final Map<String, QueuedExecutor> hostExecutors = new HashMap<String, QueuedExecutor>( ); public GridFTPClient createClient( String host, int port, CredentialProvider cp ) throws ServerException, IOException { final QueuedExecutor exec; synchronized( hostExecutors ) { if( hostExecutors.containsKey( host ) ) { log.debug( "Returning executor for host: " + host ); exec = hostExecutors.get( host ) ; } else { log.debug( "Creating executor for host: " + host ); exec = new QueuedExecutor( scheduledExecutor ); exec.setDefaultDelay( delay ); hostExecutors.put( host, exec ); } } final GridFTPClientCreator c = new GridFTPClientCreator( host, port, cp ); final Future<GridFTPClient> f = exec.submit( c ); try { try{ return f.get( exec.actualTimeout( f, timeout, unit ), unit ); } catch ( TimeoutException e ) { log.info( "GridFTPClient get() create exceeded timeout" ); f.cancel( true ); } // System.err.println( "awaiting termination" ); // exec.shutdown(); // exec.awaitTermination( timeout, TimeUnit.SECONDS ); // System.err.println( "done" ); } catch ( InterruptedException e ) { e.printStackTrace( ); throw new RuntimeException( "GridFTPClient create exceeded timeout", e ); } catch ( ExecutionException e ) { // this mustn't happen here due to the blocked wait op e.printStackTrace(); if( e.getCause() instanceof ServerException ) throw ServerException.class.cast( e.getCause() ); throw new RuntimeException( e ); } return null; } public void shutdown() { log.info( "shuting down executors" ); for( String hn: hostExecutors.keySet() ) { hostExecutors.get( hn ).shutdown(); } /* log.debug( "awaiting termination" ); for( String hn: hostExecutors.keySet() ) { try { hostExecutors.get( hn ).awaitTermination( timeout, TimeUnit.SECONDS ); } catch ( InterruptedException e ) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } */ } public int getTimeout() { return timeout; } public void setTimeout( int timeout ) { if( timeout < 0 ) throw new IllegalArgumentException( "Timeout must be greater or equal 0" ); this.timeout = timeout; } public long getDelay() { return delay; } public void setDelay( int delay ) { if( delay < 0 ) throw new IllegalArgumentException( "Delay must be greater or equal 0" ); this.delay = delay; for( String hn: hostExecutors.keySet() ) { hostExecutors.get( hn ).setDefaultDelay( delay ); } } }
kit/src/de/zib/gndms/kit/network/NonblockingClientFactory.java
package de.zib.gndms.kit.network; /* * Copyright 2008-2011 Zuse Institute Berlin (ZIB) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import de.zib.gndms.stuff.threading.QueuedExecutor; import de.zib.gndms.kit.access.CredentialProvider; import org.apache.log4j.Logger; import org.globus.ftp.GridFTPClient; import org.globus.ftp.exception.ServerException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.*; /** * @author try ma ik jo rr a zib * * @version $Id$ * <p/> * User: mjorra, Date: 20.02.2009, Time: 17:37:59 */ public class NonblockingClientFactory extends AbstractGridFTPClientFactory{ private static final Logger log = Logger.getLogger( NonblockingClientFactory.class ); private int timeout = 20; private final TimeUnit unit = TimeUnit.SECONDS; private long delay = 500; // in ms private final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool( 1 ); private final Map<String, QueuedExecutor> hostExecutors = new HashMap<String, QueuedExecutor>( ); public GridFTPClient createClient( String host, int port, CredentialProvider cp ) throws ServerException, IOException { final QueuedExecutor exec; synchronized( hostExecutors ) { if( hostExecutors.containsKey( host ) ) { log.debug( "Returning executor for host: " + host ); exec = hostExecutors.get( host ) ; } else { log.debug( "Creating executor for host: " + host ); exec = new QueuedExecutor( scheduledExecutor ); exec.setDefaultDelay( delay ); hostExecutors.put( host, exec ); } } final GridFTPClientCreator c = new GridFTPClientCreator( host, port, cp ); final Future<GridFTPClient> f = exec.submit( c ); try { try{ return f.get( exec.actualTimeout( f, timeout, unit ), unit ); } catch ( TimeoutException e ) { log.info( "GridFTPClient get() create exceeded timeout" ); f.cancel( true ); } // System.err.println( "awaiting termination" ); // exec.shutdown(); // exec.awaitTermination( timeout, TimeUnit.SECONDS ); // System.err.println( "done" ); } catch ( InterruptedException e ) { e.printStackTrace( ); throw new RuntimeException( "GridFTPClient create exceeded timeout" ); } catch ( ExecutionException e ) { // this mustn't happen here due to the blocked wait op e.printStackTrace(); } return null; } public void shutdown() { log.info( "shuting down executors" ); for( String hn: hostExecutors.keySet() ) { hostExecutors.get( hn ).shutdown(); } /* log.debug( "awaiting termination" ); for( String hn: hostExecutors.keySet() ) { try { hostExecutors.get( hn ).awaitTermination( timeout, TimeUnit.SECONDS ); } catch ( InterruptedException e ) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } */ } public int getTimeout() { return timeout; } public void setTimeout( int timeout ) { if( timeout < 0 ) throw new IllegalArgumentException( "Timeout must be greater or equal 0" ); this.timeout = timeout; } public long getDelay() { return delay; } public void setDelay( int delay ) { if( delay < 0 ) throw new IllegalArgumentException( "Delay must be greater or equal 0" ); this.delay = delay; for( String hn: hostExecutors.keySet() ) { hostExecutors.get( hn ).setDefaultDelay( delay ); } } }
fix in exception propagation
kit/src/de/zib/gndms/kit/network/NonblockingClientFactory.java
fix in exception propagation
Java
apache-2.0
c6cb1c3d7fda178e61f7c02ab10cf13d267e135a
0
Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces
package org.openspaces.admin.pu.elastic.topology; import org.openspaces.admin.pu.elastic.config.EagerScaleBeanConfig; import org.openspaces.admin.pu.elastic.config.EagerScaleBeanConfigurer; import org.openspaces.admin.pu.elastic.config.ManualContainersScaleBeanConfig; import org.openspaces.admin.pu.elastic.config.ManualContainersScaleBeanConfigurer; import org.openspaces.admin.pu.elastic.config.ManualMemoryCapacityScaleBeanConfig; import org.openspaces.admin.pu.elastic.config.ManualMemoryCapacityScaleBeanConfigurer; import org.openspaces.admin.pu.elastic.config.MemoryCapacityScaleBeanConfig; import org.openspaces.admin.pu.elastic.config.MemoryCapacityScaleBeanConfigurer; import org.openspaces.core.util.MemoryUnit; public interface ElasticStatefulDeploymentTopology extends ElasticDeploymentTopology { /** * Specifies an estimate of the maximum memory capacity for this processing unit. * The actual maximum memory capacity will be at least the specified maximum. * Requires the vmInputArgument("-Xmx...") property. * The memory capacity value is the sum of both the primary and backup instances memory capacity. */ ElasticStatefulDeploymentTopology maxMemoryCapacity(int maxMemoryCapacity, MemoryUnit unit); /** * Specifies an estimate of the minimum memory capacity for this processing unit. * The actual maximum memory capacity will be at least the specified maximum. * Requires the vmInputArgument("-Xmx...") property. * The memory capacity value is the sum of both the primary and backup instances memory capacity. */ ElasticStatefulDeploymentTopology maxMemoryCapacity(String maxMemoryCapacity); /** * Specifies an estimate of the minimum memory capacity for this processing unit. * The actual minimum memory capacity will be at least the specified minimum. * Requires the vmInputArgument("-Xmx...") property. * The memory capacity value is the sum of both the primary and backup instances memory capacity. */ ElasticStatefulDeploymentTopology minMemoryCapacity(int minMemoryCapacity, MemoryUnit unit); /** * Specifies an estimate of the minimum memory capacity for this processing unit. * The actual minimum memory capacity will be at least the specified minimum. * Requires the vmInputArgument("-Xmx...") property. * The memory capacity value is the sum of both the primary and backup instances memory capacity. */ ElasticStatefulDeploymentTopology minMemoryCapacity(String minMemoryCapacity); /** * Specifies if the space should duplicate each information on two different machines. * If set to false then partition data is lost each time fail-over or scaling occurs. * By default highlyAvailable is true */ ElasticStatefulDeploymentTopology highlyAvailable(boolean highlyAvailable); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see EagerScaleBeanConfig * @see EagerScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale(EagerScaleBeanConfigurer strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see ManualContainersScaleBeanConfig * @see ManualContainersScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( ManualContainersScaleBeanConfigurer strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see ManualMemoryCapacityScaleBeanConfig * @see ManualMemoryCapacityScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( ManualMemoryCapacityScaleBeanConfigurer strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see MemoryCapacityScaleBeanConfig * @see MemoryCapacityScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( MemoryCapacityScaleBeanConfigurer strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see EagerScaleBeanConfig * @see EagerScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale(EagerScaleBeanConfig strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see ManualContainersScaleBeanConfig * @see ManualContainersScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( ManualContainersScaleBeanConfig strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see ManualMemoryCapacityScaleBeanConfig * @see ManualMemoryCapacityScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( ManualMemoryCapacityScaleBeanConfig strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see MemoryCapacityScaleBeanConfig * @see MemoryCapacityScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( MemoryCapacityScaleBeanConfig strategy); }
src/main/src/org/openspaces/admin/pu/elastic/topology/ElasticStatefulDeploymentTopology.java
package org.openspaces.admin.pu.elastic.topology; import org.openspaces.admin.pu.elastic.config.EagerScaleBeanConfig; import org.openspaces.admin.pu.elastic.config.EagerScaleBeanConfigurer; import org.openspaces.admin.pu.elastic.config.ManualContainersScaleBeanConfig; import org.openspaces.admin.pu.elastic.config.ManualContainersScaleBeanConfigurer; import org.openspaces.admin.pu.elastic.config.ManualMemoryCapacityScaleBeanConfig; import org.openspaces.admin.pu.elastic.config.ManualMemoryCapacityScaleBeanConfigurer; import org.openspaces.admin.pu.elastic.config.MemoryCapacityScaleBeanConfig; import org.openspaces.admin.pu.elastic.config.MemoryCapacityScaleBeanConfigurer; import org.openspaces.admin.pu.elastic.config.MemoryCapacityScaleBeanConfig; import org.openspaces.admin.pu.elastic.topology.ElasticDeploymentTopology; import org.openspaces.core.util.MemoryUnit; public interface ElasticStatefulDeploymentTopology extends ElasticDeploymentTopology { /** * Specifies an estimate of the maximum memory capacity for this processing unit. * The actual maximum memory capacity will be at least the specified maximum. * Requires the vmInputArgument("-Xmx...") property. * The memory capacity value is the sum of both the primary and backup instances memory capacity. */ ElasticStatefulDeploymentTopology maxMemoryCapacity(int maxMemoryCapacity, MemoryUnit unit); /** * Specifies an estimate of the minimum memory capacity for this processing unit. * The actual maximum memory capacity will be at least the specified maximum. * Requires the vmInputArgument("-Xmx...") property. * The memory capacity value is the sum of both the primary and backup instances memory capacity. */ ElasticStatefulDeploymentTopology maxMemoryCapacity(String maxMemoryCapacity); /** * Specifies an estimate of the minimum memory capacity for this processing unit. * The actual minimum memory capacity will be at least the specified minimum. * Requires the vmInputArgument("-Xmx...") property. * The memory capacity value is the sum of both the primary and backup instances memory capacity. */ ElasticStatefulDeploymentTopology minMemoryCapacity(int minMemoryCapacity, MemoryUnit unit); /** * Specifies an estimate of the minimum memory capacity for this processing unit. * The actual minimum memory capacity will be at least the specified minimum. * Requires the vmInputArgument("-Xmx...") property. * The memory capacity value is the sum of both the primary and backup instances memory capacity. */ ElasticStatefulDeploymentTopology minMemoryCapacity(String minMemoryCapacity); /** * Specifies if the space should duplicate each information on two different machines. * If set to false then partition data is lost each time fail-over or scaling occurs. * By default highlyAvailable is true */ ElasticStatefulDeploymentTopology highlyAvailable(boolean highlyAvailable); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see EagerScaleBeanConfig * @see EagerScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale(EagerScaleBeanConfigurer strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see ManualContainersScaleBeanConfig * @see ManualContainersScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( ManualContainersScaleBeanConfigurer strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see ManualMemoryCapacityScaleBeanConfig * @see ManualMemoryCapacityScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( ManualMemoryCapacityScaleBeanConfigurer strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see MemoryCapacityScaleBeanConfig * @see MemoryCapacityScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( MemoryCapacityScaleBeanConfigurer strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see EagerScaleBeanConfig * @see EagerScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale(EagerScaleBeanConfig strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see ManualContainersScaleBeanConfig * @see ManualContainersScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( ManualContainersScaleBeanConfig strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see ManualMemoryCapacityScaleBeanConfig * @see ManualMemoryCapacityScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( ManualMemoryCapacityScaleBeanConfig strategy); /** * Enables the specified scale strategy, and disables all other scale strategies. * Scale strategies can also be reconfigured after deployment. * @see MemoryCapacityScaleBeanConfig * @see MemoryCapacityScaleBeanConfigurer */ ElasticStatefulDeploymentTopology scale( MemoryCapacityScaleBeanConfig strategy); }
removed unused import svn path=/trunk/openspaces/; revision=78777 Former-commit-id: e81fb2698b938a5fb0ea40d32902fe8a69fae556
src/main/src/org/openspaces/admin/pu/elastic/topology/ElasticStatefulDeploymentTopology.java
removed unused import
Java
apache-2.0
1bbfd05292bda27b6f6bae50e91ca4868e551ccc
0
cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x
/* * Copyright 2002-2007 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.web.portlet.mvc.annotation; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortalContext; import javax.portlet.PortletException; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import javax.portlet.PortletRequest; import javax.portlet.PortletResponse; import javax.portlet.PortletSession; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.WindowState; import org.springframework.beans.BeanUtils; import org.springframework.beans.SimpleTypeConverter; import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import org.springframework.core.MethodParameter; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.core.style.StylerUtils; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.DefaultSessionAttributeStore; import org.springframework.web.bind.support.SessionAttributeStore; import org.springframework.web.bind.support.SimpleSessionStatus; import org.springframework.web.bind.support.WebBindingInitializer; import org.springframework.web.context.request.WebRequest; import org.springframework.web.portlet.HandlerAdapter; import org.springframework.web.portlet.ModelAndView; import org.springframework.web.portlet.bind.MissingPortletRequestParameterException; import org.springframework.web.portlet.bind.PortletRequestDataBinder; import org.springframework.web.portlet.context.PortletWebRequest; import org.springframework.web.portlet.handler.PortletContentGenerator; import org.springframework.web.portlet.handler.PortletSessionRequiredException; import org.springframework.web.portlet.multipart.MultipartActionRequest; import org.springframework.web.portlet.util.PortletUtils; /** * Implementation of the {@link org.springframework.web.portlet.HandlerAdapter} * interface that maps handler methods based on portlet modes, action/render phases * and request parameters expressed through the {@link RequestMapping} annotation. * * <p>Supports request parameter binding through the {@link RequestParam} annotation. * Also supports the {@link ModelAttribute} annotation for exposing model attribute * values to the view, as well as {@link InitBinder} for binder initialization methods * and {@link SessionAttributes} for automatic session management of specific attributes. * * <p>This adapter can be customized through various bean properties. * A common use case is to apply shared binder initialization logic through * a custom {@link #setWebBindingInitializer WebBindingInitializer}. * * @author Juergen Hoeller * @author Arjen Poutsma * @since 2.5 * @see #setWebBindingInitializer * @see #setSessionAttributeStore */ public class AnnotationMethodHandlerAdapter extends PortletContentGenerator implements HandlerAdapter { private static final String IMPLICIT_MODEL_ATTRIBUTE = "org.springframework.web.portlet.mvc.ImplicitModel"; private WebBindingInitializer webBindingInitializer; private SessionAttributeStore sessionAttributeStore = new DefaultSessionAttributeStore(); private final Map<Class<?>, HandlerMethodResolver> methodResolverCache = new ConcurrentHashMap<Class<?>, HandlerMethodResolver>(); private final Map<Class<?>, Set<String>> sessionAttributeNames = new ConcurrentHashMap<Class<?>, Set<String>>(); /** * Specify a WebBindingInitializer which will apply pre-configured * configuration to every DataBinder that this controller uses. */ public void setWebBindingInitializer(WebBindingInitializer webBindingInitializer) { this.webBindingInitializer = webBindingInitializer; } /** * Specify the strategy to store session attributes with. * <p>Default is {@link org.springframework.web.bind.support.DefaultSessionAttributeStore}, * storing session attributes in the PortletSession, using the same * attribute name as in the model. */ public void setSessionAttributeStore(SessionAttributeStore sessionAttributeStore) { Assert.notNull(sessionAttributeStore, "SessionAttributeStore must not be null"); this.sessionAttributeStore = sessionAttributeStore; } public boolean supports(Object handler) { return getMethodResolver(handler.getClass()).hasHandlerMethods(); } public void handleAction(ActionRequest request, ActionResponse response, Object handler) throws Exception { Object returnValue = doHandle(request, response, handler); if (returnValue != null) { throw new IllegalStateException("Invalid action method return value: " + returnValue); } } public ModelAndView handleRender(RenderRequest request, RenderResponse response, Object handler) throws Exception { checkAndPrepare(request, response); return doHandle(request, response, handler); } protected ModelAndView doHandle(PortletRequest request, PortletResponse response, Object handler) throws Exception { ExtendedModelMap implicitModel = null; SessionAttributes sessionAttributes = handler.getClass().getAnnotation(SessionAttributes.class); Set<String> sessionAttrNames = null; if (sessionAttributes != null) { // Prepare cached set of session attributes names. sessionAttrNames = this.sessionAttributeNames.get(handler.getClass()); if (sessionAttrNames == null) { synchronized (this.sessionAttributeNames) { sessionAttrNames = this.sessionAttributeNames.get(handler.getClass()); if (sessionAttrNames == null) { sessionAttrNames = Collections.synchronizedSet(new HashSet<String>(4)); this.sessionAttributeNames.put(handler.getClass(), sessionAttrNames); } } } } if (request instanceof RenderRequest && response instanceof RenderResponse) { RenderRequest renderRequest = (RenderRequest) request; RenderResponse renderResponse = (RenderResponse) response; // Detect implicit model from associated action phase. if (renderRequest.getParameter(IMPLICIT_MODEL_ATTRIBUTE) != null) { PortletSession session = request.getPortletSession(false); if (session != null) { implicitModel = (ExtendedModelMap) session.getAttribute(IMPLICIT_MODEL_ATTRIBUTE); } } if (sessionAttributes != null) { // Always prevent caching in case of session attribute management. checkAndPrepare(renderRequest, renderResponse, 0); } else { // Uses configured default cacheSeconds setting. checkAndPrepare(renderRequest, renderResponse); } } if (implicitModel == null) { implicitModel = new ExtendedModelMap(); } WebRequest webRequest = new PortletWebRequest(request); HandlerMethodResolver methodResolver = getMethodResolver(handler.getClass()); Method handlerMethod = methodResolver.resolveHandlerMethod(request, response); ArgumentsResolver argResolver = new ArgumentsResolver(methodResolver.getInitBinderMethods()); for (Method attributeMethod : methodResolver.getModelAttributeMethods()) { Object[] args = argResolver.resolveArguments( handler, attributeMethod, request, response, webRequest, implicitModel, sessionAttrNames); ReflectionUtils.makeAccessible(attributeMethod); Object attrValue = ReflectionUtils.invokeMethod(attributeMethod, handler, args); String attrName = attributeMethod.getAnnotation(ModelAttribute.class).value(); if ("".equals(attrName)) { implicitModel.addAttribute(attrValue); } else { implicitModel.addAttribute(attrName, attrValue); } } Object[] args = argResolver.resolveArguments( handler, handlerMethod, request, response, webRequest, implicitModel, sessionAttrNames); ReflectionUtils.makeAccessible(handlerMethod); Object result = ReflectionUtils.invokeMethod(handlerMethod, handler, args); ModelAndView mav = argResolver.getModelAndView(handlerMethod, result, implicitModel); if (sessionAttributes != null) { if (argResolver.isProcessingComplete()) { if (sessionAttrNames != null) { for (String attrName : sessionAttrNames) { this.sessionAttributeStore.cleanupAttribute(webRequest, attrName); } } } // Expose model attributes as session attributes, if required. Map<String, Object> model = (mav != null ? mav.getModel() : implicitModel); Set<Object> sessionAttributeSet = new HashSet<Object>(); sessionAttributeSet.addAll(Arrays.asList(sessionAttributes.value())); sessionAttributeSet.addAll(Arrays.asList(sessionAttributes.types())); for (Map.Entry entry : new HashSet<Map.Entry>(model.entrySet())) { String attrName = (String) entry.getKey(); Object attrValue = entry.getValue(); if (sessionAttributeSet.contains(attrName) || (attrValue != null && sessionAttributeSet.contains(attrValue.getClass()))) { if (!argResolver.isProcessingComplete()) { sessionAttrNames.add(attrName); this.sessionAttributeStore.storeAttribute(webRequest, attrName, attrValue); } String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + attrName; if (mav != null && !model.containsKey(bindingResultKey)) { PortletRequestDataBinder binder = new PortletRequestDataBinder(attrValue, attrName); argResolver.initBinder(handler, attrName, binder, webRequest, request, response); mav.addObject(bindingResultKey, binder.getBindingResult()); } } } } // Expose implicit model for subsequent render phase. if (response instanceof ActionResponse && !implicitModel.isEmpty()) { ActionResponse actionResponse = (ActionResponse) response; try { actionResponse.setRenderParameter(IMPLICIT_MODEL_ATTRIBUTE, Boolean.TRUE.toString()); request.getPortletSession().setAttribute(IMPLICIT_MODEL_ATTRIBUTE, implicitModel); } catch (IllegalStateException ex) { // Probably sendRedirect called... no need to expose model to render phase. } } return mav; } private HandlerMethodResolver getMethodResolver(Class<?> handlerType) { HandlerMethodResolver resolver = this.methodResolverCache.get(handlerType); if (resolver == null) { resolver = new HandlerMethodResolver(handlerType); this.methodResolverCache.put(handlerType, resolver); } return resolver; } private static class HandlerMethodResolver { private final Set<Method> handlerMethods = new LinkedHashSet<Method>(); private final Set<Method> initBinderMethods = new LinkedHashSet<Method>(); private final Set<Method> modelAttributeMethods = new LinkedHashSet<Method>(); public HandlerMethodResolver(final Class<?> handlerType) { ReflectionUtils.doWithMethods(handlerType, new ReflectionUtils.MethodCallback() { public void doWith(Method method) { if (method.isAnnotationPresent(RequestMapping.class)) { handlerMethods.add(method); } else if (method.isAnnotationPresent(InitBinder.class)) { initBinderMethods.add(method); } else if (method.isAnnotationPresent(ModelAttribute.class)) { modelAttributeMethods.add(method); } } }); } public Method resolveHandlerMethod(PortletRequest request, PortletResponse response) { String lookupMode = request.getPortletMode().toString(); Map<RequestMappingInfo, Method> targetHandlerMethods = new LinkedHashMap<RequestMappingInfo, Method>(); for (Method handlerMethod : this.handlerMethods) { RequestMapping mapping = handlerMethod.getAnnotation(RequestMapping.class); RequestMappingInfo mappingInfo = new RequestMappingInfo(); mappingInfo.modes = mapping.value(); mappingInfo.params = mapping.params(); mappingInfo.action = isActionMethod(handlerMethod); mappingInfo.render = isRenderMethod(handlerMethod); boolean match = false; if (mappingInfo.modes.length > 0) { for (String mappedMode : mappingInfo.modes) { if (mappedMode.equalsIgnoreCase(lookupMode)) { if (checkParameters(request, response, mappingInfo)) { match = true; } else { break; } } } } else { // No modes specified: parameter match sufficient. match = checkParameters(request, response, mappingInfo); } if (match) { Method oldMappedMethod = targetHandlerMethods.put(mappingInfo, handlerMethod); if (oldMappedMethod != null && oldMappedMethod != handlerMethod) { throw new IllegalStateException("Ambiguous handler methods mapped for portlet mode '" + lookupMode + "': {" + oldMappedMethod + ", " + handlerMethod + "}. If you intend to handle the same mode in multiple methods, then factor " + "them out into a dedicated handler class with that mode mapped at the type level!"); } } } if (!targetHandlerMethods.isEmpty()) { if (targetHandlerMethods.size() == 1) { return targetHandlerMethods.values().iterator().next(); } else { RequestMappingInfo bestMappingMatch = null; for (RequestMappingInfo mapping : targetHandlerMethods.keySet()) { if (bestMappingMatch == null) { bestMappingMatch = mapping; } else { if ((bestMappingMatch.modes.length == 0 && mapping.modes.length > 0) || bestMappingMatch.params.length < mapping.params.length) { bestMappingMatch = mapping; } } } return targetHandlerMethods.get(bestMappingMatch); } } else { throw new IllegalStateException("No matching handler method found for portlet request: mode '" + request.getPortletMode() + "', type '" + (response instanceof ActionResponse ? "action" : "render") + "', parameters " + StylerUtils.style(request.getParameterMap())); } } private boolean checkParameters(PortletRequest request, PortletResponse response, RequestMappingInfo mapping) { if (response instanceof RenderResponse) { if (mapping.action) { return false; } } else if (response instanceof ActionResponse) { if (mapping.render) { return false; } } String[] params = mapping.params; if (params.length > 0) { for (String param : params) { int separator = param.indexOf('='); if (separator == -1) { if (!PortletUtils.hasSubmitParameter(request, param)) { return false; } } else { String key = param.substring(0, separator); String value = param.substring(separator + 1); if (!value.equals(request.getParameter(key))) { return false; } } } } return true; } private boolean isActionMethod(Method handlerMethod) { if (!void.class.equals(handlerMethod.getReturnType())) { return false; } for (Class<?> argType : handlerMethod.getParameterTypes()) { if (ActionRequest.class.isAssignableFrom(argType) || ActionResponse.class.isAssignableFrom(argType) || InputStream.class.isAssignableFrom(argType) || Reader.class.isAssignableFrom(argType)) { return true; } } return false; } private boolean isRenderMethod(Method handlerMethod) { if (!void.class.equals(handlerMethod.getReturnType())) { return true; } for (Class<?> argType : handlerMethod.getParameterTypes()) { if (RenderRequest.class.isAssignableFrom(argType) || RenderResponse.class.isAssignableFrom(argType) || OutputStream.class.isAssignableFrom(argType) || Writer.class.isAssignableFrom(argType)) { return true; } } return false; } public boolean hasHandlerMethods() { return !this.handlerMethods.isEmpty(); } public Set<Method> getInitBinderMethods() { return this.initBinderMethods; } public Set<Method> getModelAttributeMethods() { return this.modelAttributeMethods; } } private class ArgumentsResolver { private final Set<Method> initBinderMethods; private final SimpleSessionStatus sessionStatus = new SimpleSessionStatus(); public ArgumentsResolver(Set<Method> initBinderMethods) { this.initBinderMethods = initBinderMethods; } @SuppressWarnings("unchecked") public Object[] resolveArguments( Object handler, Method handlerMethod, PortletRequest request, PortletResponse response, WebRequest webRequest, ExtendedModelMap implicitModel, Set<String> sessionAttrNames) throws PortletException, IOException { SessionAttributes sessionAttributes = handler.getClass().getAnnotation(SessionAttributes.class); Set sessionAttributeSet = null; if (sessionAttributes != null) { sessionAttributeSet = new HashSet(); sessionAttributeSet.addAll(Arrays.asList(sessionAttributes.value())); sessionAttributeSet.addAll(Arrays.asList(sessionAttributes.types())); } SimpleTypeConverter converter = new SimpleTypeConverter(); Object[] args = new Object[handlerMethod.getParameterTypes().length]; String[] paramNames = null; boolean paramNamesResolved = false; for (int i = 0; i < args.length; i++) { MethodParameter param = new MethodParameter(handlerMethod, i); args[i] = resolveStandardArgument(param.getParameterType(), request, response, webRequest); if (args[i] == null) { if (param.getParameterType().isInstance(implicitModel)) { args[i] = implicitModel; } else if (param.getParameterType().isInstance(this.sessionStatus)) { args[i] = this.sessionStatus; } } if (args[i] == null) { boolean isParam = false; String paramName = ""; boolean paramRequired = false; String attrName = ClassUtils.getShortNameAsProperty(param.getParameterType()); Annotation[] paramAnns = (Annotation[]) param.getParameterAnnotations(); for (int j = 0; j < paramAnns.length; j++) { Annotation paramAnn = paramAnns[j]; if (RequestParam.class.isInstance(paramAnn)) { RequestParam requestParam = (RequestParam) paramAnn; isParam = true; paramName = requestParam.value(); paramRequired = requestParam.required(); break; } else if (ModelAttribute.class.isInstance(paramAnn)) { ModelAttribute attr = (ModelAttribute) paramAnn; if (!"".equals(attr.value())) { attrName = attr.value(); } } } if (isParam || BeanUtils.isSimpleProperty(param.getParameterType())) { // Request parameter value... if ("".equals(paramName)) { if (!paramNamesResolved) { ParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer(); paramNames = discoverer.getParameterNames(handlerMethod); paramNamesResolved = true; } if (paramNames == null) { throw new IllegalStateException("No parameter specified for @RequestParam argument " + "of type [" + param.getParameterType().getName() + "], and no parameter name " + "information found in class file either."); } paramName = paramNames[i]; } Object paramValue = null; if (request instanceof MultipartActionRequest) { paramValue = ((MultipartActionRequest) request).getFile(paramName); } if (paramValue == null) { paramValue = request.getParameterValues(paramName); } if (paramValue == null && paramRequired) { throw new MissingPortletRequestParameterException(paramName, param.getParameterType().getName()); } args[i] = converter.convertIfNecessary(paramValue, param.getParameterType()); } else { // Bind request parameter onto object... if (sessionAttributeSet != null && (sessionAttributeSet.contains(attrName) || sessionAttributeSet.contains(param.getParameterType())) && !implicitModel.containsKey(attrName)) { Object sessionAttr = sessionAttributeStore.retrieveAttribute(webRequest, attrName); if (sessionAttr == null) { throw new PortletSessionRequiredException( "Required session attribute '" + attrName + "' not found"); } sessionAttrNames.add(attrName); implicitModel.addAttribute(attrName, sessionAttr); } Object bindObject = implicitModel.get(attrName); if (bindObject == null) { bindObject = BeanUtils.instantiateClass(param.getParameterType()); } PortletRequestDataBinder binder = new PortletRequestDataBinder(bindObject, attrName); initBinder(handler, attrName, binder, webRequest, request, response); binder.bind(request); args[i] = bindObject; implicitModel.putAll(binder.getBindingResult().getModel()); if (args.length > i + 1 && Errors.class.isAssignableFrom(handlerMethod.getParameterTypes()[i + 1])) { args[i + 1] = binder.getBindingResult(); i++; } else { binder.closeNoCatch(); } } } } return args; } private Object resolveStandardArgument( Class<?> parameterType, PortletRequest request, PortletResponse response, WebRequest webRequest) throws IOException { if (parameterType.isInstance(request)) { return request; } else if (parameterType.isInstance(response)) { return response; } else if (PortletSession.class.isAssignableFrom(parameterType)) { return request.getPortletSession(); } else if (PortletPreferences.class.isAssignableFrom(parameterType)) { return request.getPreferences(); } else if (PortletMode.class.isAssignableFrom(parameterType)) { return request.getPortletMode(); } else if (WindowState.class.isAssignableFrom(parameterType)) { return request.getWindowState(); } else if (PortalContext.class.isAssignableFrom(parameterType)) { return request.getPortalContext(); } else if (WebRequest.class.isAssignableFrom(parameterType)) { return webRequest; } else if (Locale.class.equals(parameterType)) { return request.getLocale(); } else if (InputStream.class.equals(parameterType)) { if (!(request instanceof ActionRequest)) { throw new IllegalStateException("InputStream can only get obtained for ActionRequest"); } return ((ActionRequest) request).getPortletInputStream(); } else if (Reader.class.equals(parameterType)) { if (!(request instanceof ActionRequest)) { throw new IllegalStateException("Reader can only get obtained for ActionRequest"); } return ((ActionRequest) request).getReader(); } else if (OutputStream.class.equals(parameterType)) { if (!(response instanceof RenderResponse)) { throw new IllegalStateException("OutputStream can only get obtained for RenderResponse"); } return ((RenderResponse) response).getPortletOutputStream(); } else if (Writer.class.equals(parameterType)) { if (!(response instanceof RenderResponse)) { throw new IllegalStateException("Writer can only get obtained for RenderResponse"); } return ((RenderResponse) response).getWriter(); } else { return null; } } public void initBinder(Object handler, String attrName, WebDataBinder binder, WebRequest webRequest, PortletRequest request, PortletResponse response) throws IOException { if (webBindingInitializer != null) { webBindingInitializer.initBinder(binder, webRequest); } for (Method initBinderMethod : this.initBinderMethods) { String[] targetNames = initBinderMethod.getAnnotation(InitBinder.class).value(); if (targetNames.length == 0 || Arrays.asList(targetNames).contains(attrName)) { Class<?>[] initBinderParams = initBinderMethod.getParameterTypes(); Object[] initBinderArgs = new Object[initBinderParams.length]; for (int j = 0; j < initBinderArgs.length; j++) { initBinderArgs[j] = resolveStandardArgument( initBinderParams[j], request, response, webRequest); if (initBinderArgs[j] == null) { if (initBinderParams[j].isInstance(binder)) { initBinderArgs[j] = binder; } } } ReflectionUtils.makeAccessible(initBinderMethod); Object attrValue = ReflectionUtils.invokeMethod(initBinderMethod, handler, initBinderArgs); if (attrValue != null) { throw new IllegalStateException( "InitBinder methods must not have a return value: " + initBinderMethod); } } } } public boolean isProcessingComplete() { return this.sessionStatus.isComplete(); } @SuppressWarnings("unchecked") public ModelAndView getModelAndView(Method handlerMethod, Object returnValue, ExtendedModelMap implicitModel) { if (returnValue instanceof ModelAndView) { ModelAndView mav = (ModelAndView) returnValue; mav.getModelMap().mergeAttributes(implicitModel); return mav; } else if (returnValue instanceof Model) { return new ModelAndView().addAllObjects(implicitModel).addAllObjects(((Model) returnValue).asMap()); } else if (returnValue instanceof Map) { return new ModelAndView().addAllObjects(implicitModel).addAllObjects((Map) returnValue); } else if (returnValue instanceof String) { return new ModelAndView((String) returnValue).addAllObjects(implicitModel); } else if (returnValue == null) { // Either returned null or was 'void' return. return null; } else if (!BeanUtils.isSimpleProperty(returnValue.getClass())) { // Assume a single model attribute... String attrName = handlerMethod.getAnnotation(ModelAttribute.class).value(); ModelAndView mav = new ModelAndView().addAllObjects(implicitModel); if ("".equals(attrName)) { return mav.addObject(returnValue); } else { return mav.addObject(attrName, returnValue); } } else { throw new IllegalArgumentException("Invalid handler method return value: " + returnValue); } } } private static class RequestMappingInfo { public String[] modes = new String[0]; public String[] params = new String[0]; private boolean action = false; private boolean render = false; public boolean equals(Object obj) { RequestMappingInfo other = (RequestMappingInfo) obj; return (this.action == other.action && this.render == other.render && Arrays.equals(this.modes, other.modes) && Arrays.equals(this.params, other.params)); } public int hashCode() { return (Arrays.hashCode(this.modes) * 29 + Arrays.hashCode(this.params)); } } }
tiger/src/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
/* * Copyright 2002-2007 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.web.portlet.mvc.annotation; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortalContext; import javax.portlet.PortletException; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import javax.portlet.PortletRequest; import javax.portlet.PortletResponse; import javax.portlet.PortletSession; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.WindowState; import org.springframework.beans.BeanUtils; import org.springframework.beans.SimpleTypeConverter; import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import org.springframework.core.MethodParameter; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.core.style.StylerUtils; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.DefaultSessionAttributeStore; import org.springframework.web.bind.support.SessionAttributeStore; import org.springframework.web.bind.support.SimpleSessionStatus; import org.springframework.web.bind.support.WebBindingInitializer; import org.springframework.web.context.request.WebRequest; import org.springframework.web.portlet.HandlerAdapter; import org.springframework.web.portlet.ModelAndView; import org.springframework.web.portlet.bind.MissingPortletRequestParameterException; import org.springframework.web.portlet.bind.PortletRequestDataBinder; import org.springframework.web.portlet.context.PortletWebRequest; import org.springframework.web.portlet.handler.PortletContentGenerator; import org.springframework.web.portlet.handler.PortletSessionRequiredException; import org.springframework.web.portlet.multipart.MultipartActionRequest; import org.springframework.web.portlet.util.PortletUtils; /** * Implementation of the {@link org.springframework.web.portlet.HandlerAdapter} * interface that maps handler methods based on portlet modes, action/render phases * and request parameters expressed through the {@link RequestMapping} annotation. * * <p>Supports request parameter binding through the {@link RequestParam} annotation. * Also supports the {@link ModelAttribute} annotation for exposing model attribute * values to the view, as well as {@link InitBinder} for binder initialization methods * and {@link SessionAttributes} for automatic session management of specific attributes. * * <p>This adapter can be customized through various bean properties. * A common use case is to apply shared binder initialization logic through * a custom {@link #setWebBindingInitializer WebBindingInitializer}. * * @author Juergen Hoeller * @author Arjen Poutsma * @since 2.5 * @see #setWebBindingInitializer * @see #setSessionAttributeStore */ public class AnnotationMethodHandlerAdapter extends PortletContentGenerator implements HandlerAdapter { private static final String IMPLICIT_MODEL_ATTRIBUTE = "org.springframework.web.portlet.mvc.ImplicitModel"; private WebBindingInitializer webBindingInitializer; private SessionAttributeStore sessionAttributeStore = new DefaultSessionAttributeStore(); private final Map<Class<?>, HandlerMethodResolver> methodResolverCache = new ConcurrentHashMap<Class<?>, HandlerMethodResolver>(); private final Map<Class<?>, Set<String>> sessionAttributeNames = new ConcurrentHashMap<Class<?>, Set<String>>(); /** * Specify a WebBindingInitializer which will apply pre-configured * configuration to every DataBinder that this controller uses. */ public void setWebBindingInitializer(WebBindingInitializer webBindingInitializer) { this.webBindingInitializer = webBindingInitializer; } /** * Specify the strategy to store session attributes with. * <p>Default is {@link org.springframework.web.bind.support.DefaultSessionAttributeStore}, * storing session attributes in the PortletSession, using the same * attribute name as in the model. */ public void setSessionAttributeStore(SessionAttributeStore sessionAttributeStore) { Assert.notNull(sessionAttributeStore, "SessionAttributeStore must not be null"); this.sessionAttributeStore = sessionAttributeStore; } public boolean supports(Object handler) { return getMethodResolver(handler.getClass()).hasHandlerMethods(); } public void handleAction(ActionRequest request, ActionResponse response, Object handler) throws Exception { Object returnValue = doHandle(request, response, handler); if (returnValue != null) { throw new IllegalStateException("Invalid action method return value: " + returnValue); } } public ModelAndView handleRender(RenderRequest request, RenderResponse response, Object handler) throws Exception { checkAndPrepare(request, response); return doHandle(request, response, handler); } protected ModelAndView doHandle(PortletRequest request, PortletResponse response, Object handler) throws Exception { ExtendedModelMap implicitModel = null; SessionAttributes sessionAttributes = handler.getClass().getAnnotation(SessionAttributes.class); Set<String> sessionAttrNames = null; if (sessionAttributes != null) { // Prepare cached set of session attributes names. sessionAttrNames = this.sessionAttributeNames.get(handler.getClass()); if (sessionAttrNames == null) { synchronized (this.sessionAttributeNames) { sessionAttrNames = this.sessionAttributeNames.get(handler.getClass()); if (sessionAttrNames == null) { sessionAttrNames = Collections.synchronizedSet(new HashSet<String>(4)); this.sessionAttributeNames.put(handler.getClass(), sessionAttrNames); } } } } if (request instanceof RenderRequest) { RenderRequest renderRequest = (RenderRequest) request; RenderResponse renderResponse = (RenderResponse) response; // Detect implicit model from associated action phase. if (renderRequest.getParameter(IMPLICIT_MODEL_ATTRIBUTE) != null) { PortletSession session = request.getPortletSession(false); if (session != null) { implicitModel = (ExtendedModelMap) session.getAttribute(IMPLICIT_MODEL_ATTRIBUTE); } } if (sessionAttributes != null) { // Always prevent caching in case of session attribute management. checkAndPrepare(renderRequest, renderResponse, 0); } else { // Uses configured default cacheSeconds setting. checkAndPrepare(renderRequest, renderResponse); } } if (implicitModel == null) { implicitModel = new ExtendedModelMap(); } WebRequest webRequest = new PortletWebRequest(request); HandlerMethodResolver methodResolver = getMethodResolver(handler.getClass()); Method handlerMethod = methodResolver.resolveHandlerMethod(request); ArgumentsResolver argResolver = new ArgumentsResolver(methodResolver.getInitBinderMethods()); for (Method attributeMethod : methodResolver.getModelAttributeMethods()) { Object[] args = argResolver.resolveArguments( handler, attributeMethod, request, response, webRequest, implicitModel, sessionAttrNames); ReflectionUtils.makeAccessible(attributeMethod); Object attrValue = ReflectionUtils.invokeMethod(attributeMethod, handler, args); String attrName = attributeMethod.getAnnotation(ModelAttribute.class).value(); if ("".equals(attrName)) { implicitModel.addAttribute(attrValue); } else { implicitModel.addAttribute(attrName, attrValue); } } Object[] args = argResolver.resolveArguments( handler, handlerMethod, request, response, webRequest, implicitModel, sessionAttrNames); ReflectionUtils.makeAccessible(handlerMethod); Object result = ReflectionUtils.invokeMethod(handlerMethod, handler, args); ModelAndView mav = argResolver.getModelAndView(handlerMethod, result, implicitModel); if (sessionAttributes != null) { if (argResolver.isProcessingComplete()) { if (sessionAttrNames != null) { for (String attrName : sessionAttrNames) { this.sessionAttributeStore.cleanupAttribute(webRequest, attrName); } } } // Expose model attributes as session attributes, if required. Map<String, Object> model = (mav != null ? mav.getModel() : implicitModel); Set<Object> sessionAttributeSet = new HashSet<Object>(); sessionAttributeSet.addAll(Arrays.asList(sessionAttributes.value())); sessionAttributeSet.addAll(Arrays.asList(sessionAttributes.types())); for (Map.Entry entry : new HashSet<Map.Entry>(model.entrySet())) { String attrName = (String) entry.getKey(); Object attrValue = entry.getValue(); if (sessionAttributeSet.contains(attrName) || (attrValue != null && sessionAttributeSet.contains(attrValue.getClass()))) { if (!argResolver.isProcessingComplete()) { sessionAttrNames.add(attrName); this.sessionAttributeStore.storeAttribute(webRequest, attrName, attrValue); } String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + attrName; if (mav != null && !model.containsKey(bindingResultKey)) { PortletRequestDataBinder binder = new PortletRequestDataBinder(attrValue, attrName); argResolver.initBinder(handler, attrName, binder, webRequest, request, response); mav.addObject(bindingResultKey, binder.getBindingResult()); } } } } // Expose implicit model for subsequent render phase. if (response instanceof ActionResponse && !implicitModel.isEmpty()) { ActionResponse actionResponse = (ActionResponse) response; try { actionResponse.setRenderParameter(IMPLICIT_MODEL_ATTRIBUTE, Boolean.TRUE.toString()); request.getPortletSession().setAttribute(IMPLICIT_MODEL_ATTRIBUTE, implicitModel); } catch (IllegalStateException ex) { // Probably sendRedirect called... no need to expose model to render phase. } } return mav; } private HandlerMethodResolver getMethodResolver(Class<?> handlerType) { HandlerMethodResolver resolver = this.methodResolverCache.get(handlerType); if (resolver == null) { resolver = new HandlerMethodResolver(handlerType); this.methodResolverCache.put(handlerType, resolver); } return resolver; } private static class HandlerMethodResolver { private final Set<Method> handlerMethods = new LinkedHashSet<Method>(); private final Set<Method> initBinderMethods = new LinkedHashSet<Method>(); private final Set<Method> modelAttributeMethods = new LinkedHashSet<Method>(); public HandlerMethodResolver(final Class<?> handlerType) { ReflectionUtils.doWithMethods(handlerType, new ReflectionUtils.MethodCallback() { public void doWith(Method method) { if (method.isAnnotationPresent(RequestMapping.class)) { handlerMethods.add(method); } else if (method.isAnnotationPresent(InitBinder.class)) { initBinderMethods.add(method); } else if (method.isAnnotationPresent(ModelAttribute.class)) { modelAttributeMethods.add(method); } } }); } public Method resolveHandlerMethod(PortletRequest request) { String lookupMode = request.getPortletMode().toString(); Map<RequestMappingInfo, Method> targetHandlerMethods = new LinkedHashMap<RequestMappingInfo, Method>(); for (Method handlerMethod : this.handlerMethods) { RequestMapping mapping = handlerMethod.getAnnotation(RequestMapping.class); RequestMappingInfo mappingInfo = new RequestMappingInfo(); mappingInfo.modes = mapping.value(); mappingInfo.params = mapping.params(); mappingInfo.action = isActionMethod(handlerMethod); mappingInfo.render = isRenderMethod(handlerMethod); boolean match = false; if (mappingInfo.modes.length > 0) { for (String mappedMode : mappingInfo.modes) { if (mappedMode.equalsIgnoreCase(lookupMode)) { if (checkParameters(request, mappingInfo)) { match = true; } else { break; } } } } else { // No modes specified: parameter match sufficient. match = checkParameters(request, mappingInfo); } if (match) { Method oldMappedMethod = targetHandlerMethods.put(mappingInfo, handlerMethod); if (oldMappedMethod != null && oldMappedMethod != handlerMethod) { throw new IllegalStateException("Ambiguous handler methods mapped for portlet mode '" + lookupMode + "': {" + oldMappedMethod + ", " + handlerMethod + "}. If you intend to handle the same mode in multiple methods, then factor " + "them out into a dedicated handler class with that mode mapped at the type level!"); } } } if (!targetHandlerMethods.isEmpty()) { if (targetHandlerMethods.size() == 1) { return targetHandlerMethods.values().iterator().next(); } else { RequestMappingInfo bestMappingMatch = null; for (RequestMappingInfo mapping : targetHandlerMethods.keySet()) { if (bestMappingMatch == null) { bestMappingMatch = mapping; } else { if ((bestMappingMatch.modes.length == 0 && mapping.modes.length > 0) || bestMappingMatch.params.length < mapping.params.length) { bestMappingMatch = mapping; } } } return targetHandlerMethods.get(bestMappingMatch); } } else { throw new IllegalStateException("No matching handler method found for portlet request: mode '" + request.getPortletMode() + "', type '" + (request instanceof ActionRequest ? "action" : "render") + "', parameters " + StylerUtils.style(request.getParameterMap())); } } private boolean checkParameters(PortletRequest request, RequestMappingInfo mapping) { if (request instanceof RenderRequest) { if (mapping.action) { return false; } } else if (request instanceof ActionRequest) { if (mapping.render) { return false; } } String[] params = mapping.params; if (params.length > 0) { for (String param : params) { int separator = param.indexOf('='); if (separator == -1) { if (!PortletUtils.hasSubmitParameter(request, param)) { return false; } } else { String key = param.substring(0, separator); String value = param.substring(separator + 1); if (!value.equals(request.getParameter(key))) { return false; } } } } return true; } private boolean isActionMethod(Method handlerMethod) { if (!void.class.equals(handlerMethod.getReturnType())) { return false; } for (Class<?> argType : handlerMethod.getParameterTypes()) { if (ActionRequest.class.isAssignableFrom(argType) || ActionResponse.class.isAssignableFrom(argType) || InputStream.class.isAssignableFrom(argType) || Reader.class.isAssignableFrom(argType)) { return true; } } return false; } private boolean isRenderMethod(Method handlerMethod) { if (!void.class.equals(handlerMethod.getReturnType())) { return true; } for (Class<?> argType : handlerMethod.getParameterTypes()) { if (RenderRequest.class.isAssignableFrom(argType) || RenderResponse.class.isAssignableFrom(argType) || OutputStream.class.isAssignableFrom(argType) || Writer.class.isAssignableFrom(argType)) { return true; } } return false; } public boolean hasHandlerMethods() { return !this.handlerMethods.isEmpty(); } public Set<Method> getInitBinderMethods() { return this.initBinderMethods; } public Set<Method> getModelAttributeMethods() { return this.modelAttributeMethods; } } private class ArgumentsResolver { private final Set<Method> initBinderMethods; private final SimpleSessionStatus sessionStatus = new SimpleSessionStatus(); public ArgumentsResolver(Set<Method> initBinderMethods) { this.initBinderMethods = initBinderMethods; } @SuppressWarnings("unchecked") public Object[] resolveArguments( Object handler, Method handlerMethod, PortletRequest request, PortletResponse response, WebRequest webRequest, ExtendedModelMap implicitModel, Set<String> sessionAttrNames) throws PortletException, IOException { SessionAttributes sessionAttributes = handler.getClass().getAnnotation(SessionAttributes.class); Set sessionAttributeSet = null; if (sessionAttributes != null) { sessionAttributeSet = new HashSet(); sessionAttributeSet.addAll(Arrays.asList(sessionAttributes.value())); sessionAttributeSet.addAll(Arrays.asList(sessionAttributes.types())); } SimpleTypeConverter converter = new SimpleTypeConverter(); Object[] args = new Object[handlerMethod.getParameterTypes().length]; String[] paramNames = null; boolean paramNamesResolved = false; for (int i = 0; i < args.length; i++) { MethodParameter param = new MethodParameter(handlerMethod, i); args[i] = resolveStandardArgument(param.getParameterType(), request, response, webRequest); if (args[i] == null) { if (param.getParameterType().isInstance(implicitModel)) { args[i] = implicitModel; } else if (param.getParameterType().isInstance(this.sessionStatus)) { args[i] = this.sessionStatus; } } if (args[i] == null) { boolean isParam = false; String paramName = ""; boolean paramRequired = false; String attrName = ClassUtils.getShortNameAsProperty(param.getParameterType()); Annotation[] paramAnns = (Annotation[]) param.getParameterAnnotations(); for (int j = 0; j < paramAnns.length; j++) { Annotation paramAnn = paramAnns[j]; if (RequestParam.class.isInstance(paramAnn)) { RequestParam requestParam = (RequestParam) paramAnn; isParam = true; paramName = requestParam.value(); paramRequired = requestParam.required(); break; } else if (ModelAttribute.class.isInstance(paramAnn)) { ModelAttribute attr = (ModelAttribute) paramAnn; if (!"".equals(attr.value())) { attrName = attr.value(); } } } if (isParam || BeanUtils.isSimpleProperty(param.getParameterType())) { // Request parameter value... if ("".equals(paramName)) { if (!paramNamesResolved) { ParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer(); paramNames = discoverer.getParameterNames(handlerMethod); paramNamesResolved = true; } if (paramNames == null) { throw new IllegalStateException("No parameter specified for @RequestParam argument " + "of type [" + param.getParameterType().getName() + "], and no parameter name " + "information found in class file either."); } paramName = paramNames[i]; } Object paramValue = null; if (request instanceof MultipartActionRequest) { paramValue = ((MultipartActionRequest) request).getFile(paramName); } if (paramValue == null) { paramValue = request.getParameterValues(paramName); } if (paramValue == null && paramRequired) { throw new MissingPortletRequestParameterException(paramName, param.getParameterType().getName()); } args[i] = converter.convertIfNecessary(paramValue, param.getParameterType()); } else { // Bind request parameter onto object... if (sessionAttributeSet != null && (sessionAttributeSet.contains(attrName) || sessionAttributeSet.contains(param.getParameterType())) && !implicitModel.containsKey(attrName)) { Object sessionAttr = sessionAttributeStore.retrieveAttribute(webRequest, attrName); if (sessionAttr == null) { throw new PortletSessionRequiredException( "Required session attribute '" + attrName + "' not found"); } sessionAttrNames.add(attrName); implicitModel.addAttribute(attrName, sessionAttr); } Object bindObject = implicitModel.get(attrName); if (bindObject == null) { bindObject = BeanUtils.instantiateClass(param.getParameterType()); } PortletRequestDataBinder binder = new PortletRequestDataBinder(bindObject, attrName); initBinder(handler, attrName, binder, webRequest, request, response); binder.bind(request); args[i] = bindObject; implicitModel.putAll(binder.getBindingResult().getModel()); if (args.length > i + 1 && Errors.class.isAssignableFrom(handlerMethod.getParameterTypes()[i + 1])) { args[i + 1] = binder.getBindingResult(); i++; } else { binder.closeNoCatch(); } } } } return args; } private Object resolveStandardArgument( Class<?> parameterType, PortletRequest request, PortletResponse response, WebRequest webRequest) throws IOException { if (parameterType.isInstance(request)) { return request; } else if (parameterType.isInstance(response)) { return response; } else if (PortletSession.class.isAssignableFrom(parameterType)) { return request.getPortletSession(); } else if (PortletPreferences.class.isAssignableFrom(parameterType)) { return request.getPreferences(); } else if (PortletMode.class.isAssignableFrom(parameterType)) { return request.getPortletMode(); } else if (WindowState.class.isAssignableFrom(parameterType)) { return request.getWindowState(); } else if (PortalContext.class.isAssignableFrom(parameterType)) { return request.getPortalContext(); } else if (WebRequest.class.isAssignableFrom(parameterType)) { return webRequest; } else if (Locale.class.equals(parameterType)) { return request.getLocale(); } else if (InputStream.class.equals(parameterType)) { if (!(request instanceof ActionRequest)) { throw new IllegalStateException("InputStream can only get obtained for ActionRequest"); } return ((ActionRequest) request).getPortletInputStream(); } else if (Reader.class.equals(parameterType)) { if (!(request instanceof ActionRequest)) { throw new IllegalStateException("Reader can only get obtained for ActionRequest"); } return ((ActionRequest) request).getReader(); } else if (OutputStream.class.equals(parameterType)) { if (!(response instanceof RenderResponse)) { throw new IllegalStateException("OutputStream can only get obtained for RenderResponse"); } return ((RenderResponse) response).getPortletOutputStream(); } else if (Writer.class.equals(parameterType)) { if (!(response instanceof RenderResponse)) { throw new IllegalStateException("Writer can only get obtained for RenderResponse"); } return ((RenderResponse) response).getWriter(); } else { return null; } } public void initBinder(Object handler, String attrName, WebDataBinder binder, WebRequest webRequest, PortletRequest request, PortletResponse response) throws IOException { if (webBindingInitializer != null) { webBindingInitializer.initBinder(binder, webRequest); } for (Method initBinderMethod : this.initBinderMethods) { String[] targetNames = initBinderMethod.getAnnotation(InitBinder.class).value(); if (targetNames.length == 0 || Arrays.asList(targetNames).contains(attrName)) { Class<?>[] initBinderParams = initBinderMethod.getParameterTypes(); Object[] initBinderArgs = new Object[initBinderParams.length]; for (int j = 0; j < initBinderArgs.length; j++) { initBinderArgs[j] = resolveStandardArgument( initBinderParams[j], request, response, webRequest); if (initBinderArgs[j] == null) { if (initBinderParams[j].isInstance(binder)) { initBinderArgs[j] = binder; } } } ReflectionUtils.makeAccessible(initBinderMethod); Object attrValue = ReflectionUtils.invokeMethod(initBinderMethod, handler, initBinderArgs); if (attrValue != null) { throw new IllegalStateException( "InitBinder methods must not have a return value: " + initBinderMethod); } } } } public boolean isProcessingComplete() { return this.sessionStatus.isComplete(); } @SuppressWarnings("unchecked") public ModelAndView getModelAndView(Method handlerMethod, Object returnValue, ExtendedModelMap implicitModel) { if (returnValue instanceof ModelAndView) { ModelAndView mav = (ModelAndView) returnValue; mav.getModelMap().mergeAttributes(implicitModel); return mav; } else if (returnValue instanceof Model) { return new ModelAndView().addAllObjects(implicitModel).addAllObjects(((Model) returnValue).asMap()); } else if (returnValue instanceof Map) { return new ModelAndView().addAllObjects(implicitModel).addAllObjects((Map) returnValue); } else if (returnValue instanceof String) { return new ModelAndView((String) returnValue).addAllObjects(implicitModel); } else if (returnValue == null) { // Either returned null or was 'void' return. return null; } else if (!BeanUtils.isSimpleProperty(returnValue.getClass())) { // Assume a single model attribute... String attrName = handlerMethod.getAnnotation(ModelAttribute.class).value(); ModelAndView mav = new ModelAndView().addAllObjects(implicitModel); if ("".equals(attrName)) { return mav.addObject(returnValue); } else { return mav.addObject(attrName, returnValue); } } else { throw new IllegalArgumentException("Invalid handler method return value: " + returnValue); } } } private static class RequestMappingInfo { public String[] modes = new String[0]; public String[] params = new String[0]; private boolean action = false; private boolean render = false; public boolean equals(Object obj) { RequestMappingInfo other = (RequestMappingInfo) obj; return (this.action == other.action && this.render == other.render && Arrays.equals(this.modes, other.modes) && Arrays.equals(this.params, other.params)); } public int hashCode() { return (Arrays.hashCode(this.modes) * 29 + Arrays.hashCode(this.params)); } } }
fixed Portlet AnnotationMethodHandlerAdapter to explicitly check for Action/Render*Response* (to work on Liferay) git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@15702 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
tiger/src/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
fixed Portlet AnnotationMethodHandlerAdapter to explicitly check for Action/Render*Response* (to work on Liferay)
Java
apache-2.0
75317d2ea7f9cf0046ef03683610e156fc21d62b
0
lchli/LiteHotfix
package com.lchli.litehotfix; import android.content.Context; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.text.TextUtils; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Properties; import dalvik.system.PathClassLoader; /** * Created by lchli on 2017/2/21. * <p> * 轻量级dex热修复。 * 1,不支持资源文件更改。 * 2,不支持manifest文件修改。 * 3,不支持so库修改。 * 4,不支持Application类修改(因为此类在hook之前就已经加载)。 */ public class HotFix { public static boolean DEBUG = true; private String patchDex; private String patchDirectory; private String infoFilePath; private int currentAppVersion; private String dexoptPath; private static volatile HotFix fix; private HotFix() { } public static HotFix instance() { if (fix != null) { return fix; } synchronized (HotFix.class) { if (fix == null) { fix = new HotFix(); } } return fix; } private void initSetting(Context base) { try { currentAppVersion = base.getPackageManager().getPackageInfo(base.getPackageName(), PackageManager.GET_CONFIGURATIONS).versionCode; log("parse currentAppVersion=" + currentAppVersion); File patchDir = new File(base.getCacheDir().getParentFile(), "patch"); if (!patchDir.exists()) { patchDir.mkdirs(); } patchDirectory = patchDir.getAbsolutePath(); File info = new File(patchDirectory, "p.properties"); if (!info.exists()) { info.createNewFile(); } infoFilePath = info.getAbsolutePath(); File dex = new File(patchDir, "patch.dex"); patchDex = dex.getAbsolutePath(); final File dexopt = new File(base.getCacheDir().getParentFile(), "dexopt"); if (!dexopt.exists()) { dexopt.mkdirs(); } dexoptPath = dexopt.getAbsolutePath(); } catch (Exception e) { e.printStackTrace(); } } /*** * should call this on {@code Application#attachBaseContext} */ public void init(Context base) { try { initSetting(base); final File dex = new File(patchDex); if (!dex.exists()) { log("no patch dex file"); return;//no patch,so we do not install. } PatchInfo patchInfo = getPatchInfo(); if (patchInfo == null || patchInfo.targetAppVersion != currentAppVersion) { dex.delete();//delete expired dex. log("patch dex file is expired."); return; } //change class loader,s parent loader. Class<?> class_ActivityThread = Class.forName("android.app.ActivityThread"); Method method_currentActivityThread = class_ActivityThread.getDeclaredMethod("currentActivityThread"); method_currentActivityThread.setAccessible(true); Object currentActivityThread = method_currentActivityThread.invoke(null); final Class<?> cls = currentActivityThread.getClass(); Field field_mPackages = cls.getDeclaredField("mPackages"); field_mPackages.setAccessible(true); Object mPackagesObj = field_mPackages.get(currentActivityThread); Method method_get = mPackagesObj.getClass().getDeclaredMethod("get", Object.class); method_get.setAccessible(true); final WeakReference loadedApkRef = (WeakReference) method_get.invoke(mPackagesObj, base.getPackageName()); Object loadedApk = loadedApkRef.get(); Field field_mClassLoader = loadedApk.getClass().getDeclaredField("mClassLoader"); field_mClassLoader.setAccessible(true); final PathClassLoader originLoader = (PathClassLoader) field_mClassLoader.get(loadedApk); Field field_parent = ClassLoader.class.getDeclaredField("parent"); field_parent.setAccessible(true); //use a proxy to replace originLoader. field_mClassLoader.set(loadedApk, new FixClassLoader(originLoader)); } catch (Exception e) { e.printStackTrace(); } } /** * hook {@code findClass} method. */ private class FixClassLoader extends ClassLoader { private ClassLoader delegate; private Object dexPathList; private Method m_findClass; private List<Throwable> suppressedExceptions = new ArrayList<>(); public FixClassLoader(ClassLoader delegate) { this.delegate = delegate; try { Class<?> cls_DexPathList = Class.forName("dalvik.system.DexPathList"); Constructor<?> cons_DexPathList = cls_DexPathList.getDeclaredConstructor(ClassLoader.class, String.class, String.class, File.class); cons_DexPathList.setAccessible(true); dexPathList = cons_DexPathList.newInstance(delegate, patchDex, patchDex, new File(dexoptPath)); m_findClass = cls_DexPathList.getDeclaredMethod("findClass", String.class, List.class); m_findClass.setAccessible(true); } catch (Exception e) { e.printStackTrace(); } } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { Class fixedClass = (Class) m_findClass.invoke(dexPathList, name, suppressedExceptions);//load fix class first. if (fixedClass != null) { return fixedClass; } throw new ClassNotFoundException(); } catch (Exception e) { try { Method m_findClass = delegate.getClass().getDeclaredMethod("findClass", String.class);//load original class. m_findClass.setAccessible(true); return (Class<?>) m_findClass.invoke(delegate, name); } catch (Exception e2) { throw new ClassNotFoundException(e2.getMessage()); } } } } /*** * copy pathDex to data dir,if already exists one,it will be override. * * @param patchDexPath * @param targetAppVersion * @param patchVersion * @param cb */ public void installPatch(final String patchDexPath, final int targetAppVersion, final int patchVersion, final InstallPatchCallback cb) { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { return installPatchImpl(patchDexPath, targetAppVersion, patchVersion); } @Override protected void onPostExecute(Boolean aBoolean) { cb.onFinish(aBoolean); } }.execute(); } private boolean installPatchImpl(String patchDexPath, int targetAppVersion, int patchVersion) { if (patchDexPath == null) { throw new IllegalArgumentException("patchDexPath can not be null."); } if (targetAppVersion != currentAppVersion) { log("targetAppVersion not match."); return false; } PatchInfo patchInfo = getPatchInfo(); if (patchInfo != null && patchInfo.patchVersion == patchVersion) { log("patch already installed."); return false;//already installed. } File p = new File(infoFilePath); FileWriter fileWriter = null; try { FileUtils.copyFile(new File(patchDexPath), new File(patchDex)); fileWriter = new FileWriter(p); Properties properties = new Properties(); properties.setProperty(PatchInfo.field_targetAppVersion, targetAppVersion + ""); properties.setProperty(PatchInfo.field_patchVersion, patchVersion + ""); properties.store(fileWriter, ""); log("---------------install patch success,please restart process......."); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static void log(String msg) { if (DEBUG) { System.err.println("[*****************************]" + msg); } } private PatchInfo getPatchInfo() { File info = new File(infoFilePath); FileReader fileReader = null; try { fileReader = new FileReader(info); Properties properties = new Properties(); properties.load(fileReader); String dexTarget = properties.getProperty(PatchInfo.field_targetAppVersion); if (TextUtils.isEmpty(dexTarget)) { return null; } String pathVersion = properties.getProperty(PatchInfo.field_patchVersion); if (TextUtils.isEmpty(pathVersion)) { return null; } PatchInfo patchInfo = new PatchInfo(); patchInfo.targetAppVersion = Integer.parseInt(dexTarget); patchInfo.patchVersion = Integer.parseInt(pathVersion); return patchInfo; } catch (Exception e) { e.printStackTrace(); return null; } finally { if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static class PatchInfo { private int targetAppVersion; private int patchVersion; private static final String field_targetAppVersion = "targetAppVersion"; private static final String field_patchVersion = "patchVersion"; } public interface InstallPatchCallback { void onFinish(boolean isSuccess); } }
hotfix/litehotfix/src/main/java/com/lchli/litehotfix/HotFix.java
package com.lchli.litehotfix; import android.content.Context; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.text.TextUtils; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Properties; import dalvik.system.PathClassLoader; /** * Created by lchli on 2017/2/21. * <p> * 轻量级dex热修复。 * 1,不支持资源文件更改。 * 2,不支持manifest文件修改。 * 3,不支持so库修改。 * 4,不支持Application类修改(因为此类在hook之前就已经加载)。 */ public class HotFix { private String patchDex; private String patchDirectory; private String infoFilePath; private int currentAppVersion; private String dexoptPath; private static volatile HotFix fix; private HotFix() { } public static HotFix instance() { if (fix != null) { return fix; } synchronized (HotFix.class) { if (fix == null) { fix = new HotFix(); } } return fix; } private void initSetting(Context base) { try { currentAppVersion = base.getPackageManager().getPackageInfo(base.getPackageName(), PackageManager.GET_CONFIGURATIONS).versionCode; log("parse currentAppVersion=" + currentAppVersion); File patchDir = new File(base.getCacheDir().getParentFile(), "patch"); if (!patchDir.exists()) { patchDir.mkdirs(); } patchDirectory = patchDir.getAbsolutePath(); File info = new File(patchDirectory, "p.properties"); if (!info.exists()) { info.createNewFile(); } infoFilePath = info.getAbsolutePath(); File dex = new File(patchDir, "patch.dex"); patchDex = dex.getAbsolutePath(); final File dexopt = new File(base.getCacheDir().getParentFile(), "dexopt"); if (!dexopt.exists()) { dexopt.mkdirs(); } dexoptPath = dexopt.getAbsolutePath(); } catch (Exception e) { e.printStackTrace(); } } /*** * should call this on {@code Application#attachBaseContext} */ public void init(Context base) { try { initSetting(base); final File dex = new File(patchDex); if (!dex.exists()) { log("no patch dex file"); return;//no patch,so we do not install. } PatchInfo patchInfo = getPatchInfo(); if (patchInfo == null || patchInfo.targetAppVersion != currentAppVersion) { dex.delete();//delete expired dex. log("patch dex file is expired."); return; } //change class loader,s parent loader. Class<?> class_ActivityThread = Class.forName("android.app.ActivityThread"); Method method_currentActivityThread = class_ActivityThread.getDeclaredMethod("currentActivityThread"); method_currentActivityThread.setAccessible(true); Object currentActivityThread = method_currentActivityThread.invoke(null); final Class<?> cls = currentActivityThread.getClass(); Field field_mPackages = cls.getDeclaredField("mPackages"); field_mPackages.setAccessible(true); Object mPackagesObj = field_mPackages.get(currentActivityThread); Method method_get = mPackagesObj.getClass().getDeclaredMethod("get", Object.class); method_get.setAccessible(true); final WeakReference loadedApkRef = (WeakReference) method_get.invoke(mPackagesObj, base.getPackageName()); Object loadedApk = loadedApkRef.get(); Field field_mClassLoader = loadedApk.getClass().getDeclaredField("mClassLoader"); field_mClassLoader.setAccessible(true); final PathClassLoader originLoader = (PathClassLoader) field_mClassLoader.get(loadedApk); Field field_parent = ClassLoader.class.getDeclaredField("parent"); field_parent.setAccessible(true); //use a proxy to replace originLoader. field_mClassLoader.set(loadedApk, new FixClassLoader(originLoader)); } catch (Exception e) { e.printStackTrace(); } } /** * hook {@code findClass} method. */ private class FixClassLoader extends ClassLoader { private ClassLoader delegate; private Object dexPathList; private Method m_findClass; private List<Throwable> suppressedExceptions = new ArrayList<>(); public FixClassLoader(ClassLoader delegate) { this.delegate = delegate; try { Class<?> cls_DexPathList = Class.forName("dalvik.system.DexPathList"); Constructor<?> cons_DexPathList = cls_DexPathList.getDeclaredConstructor(ClassLoader.class, String.class, String.class, File.class); cons_DexPathList.setAccessible(true); dexPathList = cons_DexPathList.newInstance(delegate, patchDex, patchDex, new File(dexoptPath)); m_findClass = cls_DexPathList.getDeclaredMethod("findClass", String.class, List.class); m_findClass.setAccessible(true); } catch (Exception e) { e.printStackTrace(); } } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { Class fixedClass = (Class) m_findClass.invoke(dexPathList, name, suppressedExceptions);//load fix class first. if (fixedClass != null) { return fixedClass; } throw new ClassNotFoundException(); } catch (Exception e) { try { Method m_findClass = delegate.getClass().getDeclaredMethod("findClass", String.class);//load original class. m_findClass.setAccessible(true); return (Class<?>) m_findClass.invoke(delegate, name); } catch (Exception e2) { throw new ClassNotFoundException(e2.getMessage()); } } } } /*** * copy pathDex to data dir,if already exists one,it will be override. * * @param patchDexPath * @param targetAppVersion * @param patchVersion * @param cb */ public void installPatch(final String patchDexPath, final int targetAppVersion, final int patchVersion, final InstallPatchCallback cb) { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { return installPatchImpl(patchDexPath, targetAppVersion, patchVersion); } @Override protected void onPostExecute(Boolean aBoolean) { cb.onFinish(aBoolean); } }.execute(); } private boolean installPatchImpl(String patchDexPath, int targetAppVersion, int patchVersion) { if (patchDexPath == null) { throw new IllegalArgumentException("patchDexPath can not be null."); } if (targetAppVersion != currentAppVersion) { log("targetAppVersion not match."); return false; } PatchInfo patchInfo = getPatchInfo(); if (patchInfo != null && patchInfo.patchVersion == patchVersion) { log("patch already installed."); return false;//already installed. } File p = new File(infoFilePath); FileWriter fileWriter = null; try { FileUtils.copyFile(new File(patchDexPath), new File(patchDex)); fileWriter = new FileWriter(p); Properties properties = new Properties(); properties.setProperty(PatchInfo.field_targetAppVersion, targetAppVersion + ""); properties.setProperty(PatchInfo.field_patchVersion, patchVersion + ""); properties.store(fileWriter, ""); log("---------------install patch success,please restart process......."); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static void log(String msg) { System.err.println("[*****************************]" + msg); } private PatchInfo getPatchInfo() { File info = new File(infoFilePath); FileReader fileReader = null; try { fileReader = new FileReader(info); Properties properties = new Properties(); properties.load(fileReader); String dexTarget = properties.getProperty(PatchInfo.field_targetAppVersion); if (TextUtils.isEmpty(dexTarget)) { return null; } String pathVersion = properties.getProperty(PatchInfo.field_patchVersion); if (TextUtils.isEmpty(pathVersion)) { return null; } PatchInfo patchInfo = new PatchInfo(); patchInfo.targetAppVersion = Integer.parseInt(dexTarget); patchInfo.patchVersion = Integer.parseInt(pathVersion); return patchInfo; } catch (Exception e) { e.printStackTrace(); return null; } finally { if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static class PatchInfo { private int targetAppVersion; private int patchVersion; private static final String field_targetAppVersion = "targetAppVersion"; private static final String field_patchVersion = "patchVersion"; } public interface InstallPatchCallback { void onFinish(boolean isSuccess); } }
add log switch.
hotfix/litehotfix/src/main/java/com/lchli/litehotfix/HotFix.java
add log switch.
Java
bsd-2-clause
b56beb72732b5b395bcf99464c056dd6a64e14ba
0
clintonhealthaccess/chailmis-android,jason-p-pickering/chailmis-android,jason-p-pickering/chailmis-android,clintonhealthaccess/chailmis-android,clintonhealthaccess/chailmis-android,clintonhealthaccess/chailmis-android,jason-p-pickering/chailmis-android,clintonhealthaccess/chailmis-android,jason-p-pickering/chailmis-android,jason-p-pickering/chailmis-android
/* * Copyright (c) 2014, Thoughtworks Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. */ package org.clintonhealthaccess.lmis.app.adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import org.clintonhealthaccess.lmis.app.R; import org.clintonhealthaccess.lmis.app.activities.viewmodels.LossesCommodityViewModel; import org.clintonhealthaccess.lmis.app.events.CommodityToggledEvent; import org.clintonhealthaccess.lmis.app.models.Commodity; import org.clintonhealthaccess.lmis.utils.RobolectricGradleTestRunner; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import java.util.Arrays; import java.util.List; import de.greenrobot.event.EventBus; import static com.google.common.collect.Lists.newArrayList; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static org.clintonhealthaccess.lmis.app.models.LossReason.EXPIRED; import static org.clintonhealthaccess.lmis.app.models.LossReason.MISSING; import static org.clintonhealthaccess.lmis.app.models.LossReason.WASTED; import static org.clintonhealthaccess.lmis.app.utils.ViewHelpers.getIntFromString; import static org.clintonhealthaccess.lmis.utils.ListTestUtils.getViewFromListRow; import static org.clintonhealthaccess.lmis.utils.TestFixture.buildMockCommodity; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.mockito.Mockito.when; @RunWith(RobolectricGradleTestRunner.class) public class LossesCommoditiesAdapterTest { boolean toggleEventFired = false; private int list_item_layout; private LossesCommoditiesAdapter adapter; private Commodity mockCommodity; @Before public void setUp() { mockCommodity = buildMockCommodity(); when(mockCommodity.getStockOnHand()).thenReturn(10000); List<LossesCommodityViewModel> commodities = Arrays.asList(new LossesCommodityViewModel(mockCommodity)); list_item_layout = R.layout.losses_commodity_list_item; adapter = new LossesCommoditiesAdapter(Robolectric.application, list_item_layout, commodities); EventBus.getDefault().register(this); } @Test public void shouldSetViewModelParametersOnEditTextInput() { List<EditText> allInputFields = getAllInputFields(adapter, list_item_layout); allInputFields.get(0).setText("10"); allInputFields.get(1).setText("20"); allInputFields.get(2).setText("30"); LossesCommodityViewModel viewModel = adapter.getItem(0); assertThat(viewModel.getLoss(EXPIRED), is(10)); assertThat(viewModel.getLoss(WASTED), is(20)); assertThat(viewModel.getLoss(MISSING), is(30)); } @Test public void shouldToggleItemOnCancelButtonClick() { ImageButton cancelButton = (ImageButton) getViewFromListRow(adapter, list_item_layout, R.id.imageButtonCancel); assertThat(adapter.getCount(), is(1)); cancelButton.performClick(); assertTrue(toggleEventFired); } @Test public void shouldPreLoadEditTextsWithValuesInViewModels() { Commodity commodity = buildMockCommodity(); LossesCommodityViewModel lossesCommodityViewModel = new LossesCommodityViewModel(commodity); lossesCommodityViewModel.setLoss(WASTED, 3); lossesCommodityViewModel.setLoss(MISSING, 1); lossesCommodityViewModel.setLoss(EXPIRED, 4); List<LossesCommodityViewModel> commodities = Arrays.asList(lossesCommodityViewModel); list_item_layout = R.layout.losses_commodity_list_item; adapter = new LossesCommoditiesAdapter(Robolectric.application, list_item_layout, commodities); List<EditText> allInputFields = getAllInputFields(adapter, list_item_layout); int expiries = getIntFromString(allInputFields.get(0).getText().toString()); int wastages = getIntFromString(allInputFields.get(1).getText().toString()); int missing = getIntFromString(allInputFields.get(2).getText().toString()); assertThat(wastages, is(3)); assertThat(missing, is(1)); assertThat(expiries, is(4)); } @Ignore("WIP - Job") @Test public void shouldSetErrorsOnCommodityIfTotalLossesAreGreaterThanStockOnHand() { when(mockCommodity.getStockOnHand()).thenReturn(10); List<EditText> allInputFields = getAllInputFields(adapter, list_item_layout); allInputFields.get(1).setText("8"); TextView textViewCommodityName = (TextView)getViewFromListRow(adapter, list_item_layout, R.id.textViewCommodityName); assertNull(textViewCommodityName.getError()); assertThat(textViewCommodityName.getError().toString(), is("Total quantity lost (18) is greater than stock at hand (10)")); assertNull(textViewCommodityName.getError()); } public void onEvent(CommodityToggledEvent event) { if (!event.getCommodity().isSelected()) { toggleEventFired = true; } } private List<EditText> getAllInputFields(ArrayAdapter adapter, int row_layout) { List<EditText> results = newArrayList(); ViewGroup genericLayout = new LinearLayout(Robolectric.application); View convertView = LayoutInflater.from(Robolectric.application).inflate(row_layout, null); ViewGroup row = (ViewGroup) adapter.getView(0, convertView, genericLayout); LinearLayout inputsLinearLayout = (LinearLayout) row.getChildAt(2); for (int i = 0; i < inputsLinearLayout.getChildCount(); i++) { View childView = inputsLinearLayout.getChildAt(i); if (childView instanceof EditText) { results.add((EditText) childView); } } return results; } }
app/src/test/java/org/clintonhealthaccess/lmis/app/adapters/LossesCommoditiesAdapterTest.java
/* * Copyright (c) 2014, Thoughtworks Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. */ package org.clintonhealthaccess.lmis.app.adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import org.clintonhealthaccess.lmis.app.R; import org.clintonhealthaccess.lmis.app.activities.viewmodels.LossesCommodityViewModel; import org.clintonhealthaccess.lmis.app.events.CommodityToggledEvent; import org.clintonhealthaccess.lmis.app.models.Commodity; import org.clintonhealthaccess.lmis.utils.RobolectricGradleTestRunner; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import java.util.Arrays; import java.util.List; import de.greenrobot.event.EventBus; import static com.google.common.collect.Lists.newArrayList; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static org.clintonhealthaccess.lmis.app.models.LossReason.EXPIRED; import static org.clintonhealthaccess.lmis.app.models.LossReason.MISSING; import static org.clintonhealthaccess.lmis.app.models.LossReason.WASTED; import static org.clintonhealthaccess.lmis.app.utils.ViewHelpers.getIntFromString; import static org.clintonhealthaccess.lmis.utils.ListTestUtils.getViewFromListRow; import static org.clintonhealthaccess.lmis.utils.TestFixture.buildMockCommodity; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.mockito.Mockito.when; @RunWith(RobolectricGradleTestRunner.class) public class LossesCommoditiesAdapterTest { boolean toggleEventFired = false; private int list_item_layout; private LossesCommoditiesAdapter adapter; private Commodity mockCommodity; @Before public void setUp() { mockCommodity = buildMockCommodity(); when(mockCommodity.getStockOnHand()).thenReturn(10000); List<LossesCommodityViewModel> commodities = Arrays.asList(new LossesCommodityViewModel(mockCommodity)); list_item_layout = R.layout.losses_commodity_list_item; adapter = new LossesCommoditiesAdapter(Robolectric.application, list_item_layout, commodities); EventBus.getDefault().register(this); } @Test public void shouldSetViewModelParametersOnEditTextInput() { List<EditText> allInputFields = getAllInputFields(adapter, list_item_layout); allInputFields.get(0).setText("10"); allInputFields.get(1).setText("20"); allInputFields.get(2).setText("30"); LossesCommodityViewModel viewModel = adapter.getItem(0); assertThat(viewModel.getLoss(WASTED), is(10)); assertThat(viewModel.getLoss(MISSING), is(20)); assertThat(viewModel.getLoss(EXPIRED), is(30)); } @Test public void shouldToggleItemOnCancelButtonClick() { ImageButton cancelButton = (ImageButton) getViewFromListRow(adapter, list_item_layout, R.id.imageButtonCancel); assertThat(adapter.getCount(), is(1)); cancelButton.performClick(); assertTrue(toggleEventFired); } @Test public void shouldPreLoadEditTextsWithValuesInViewModels() { Commodity commodity = buildMockCommodity(); LossesCommodityViewModel lossesCommodityViewModel = new LossesCommodityViewModel(commodity); lossesCommodityViewModel.setLoss(WASTED, 3); lossesCommodityViewModel.setLoss(MISSING, 1); lossesCommodityViewModel.setLoss(EXPIRED, 4); List<LossesCommodityViewModel> commodities = Arrays.asList(lossesCommodityViewModel); list_item_layout = R.layout.losses_commodity_list_item; adapter = new LossesCommoditiesAdapter(Robolectric.application, list_item_layout, commodities); List<EditText> allInputFields = getAllInputFields(adapter, list_item_layout); int wastages = getIntFromString(allInputFields.get(0).getText().toString()); int missing = getIntFromString(allInputFields.get(1).getText().toString()); int expiries = getIntFromString(allInputFields.get(2).getText().toString()); assertThat(wastages, is(3)); assertThat(missing, is(1)); assertThat(expiries, is(4)); } @Ignore("WIP - Job") @Test public void shouldSetErrorsOnCommodityIfTotalLossesAreGreaterThanStockOnHand() { when(mockCommodity.getStockOnHand()).thenReturn(10); List<EditText> allInputFields = getAllInputFields(adapter, list_item_layout); allInputFields.get(1).setText("8"); TextView textViewCommodityName = (TextView)getViewFromListRow(adapter, list_item_layout, R.id.textViewCommodityName); assertNull(textViewCommodityName.getError()); assertThat(textViewCommodityName.getError().toString(), is("Total quantity lost (18) is greater than stock at hand (10)")); assertNull(textViewCommodityName.getError()); } public void onEvent(CommodityToggledEvent event) { if (!event.getCommodity().isSelected()) { toggleEventFired = true; } } private List<EditText> getAllInputFields(ArrayAdapter adapter, int row_layout) { List<EditText> results = newArrayList(); ViewGroup genericLayout = new LinearLayout(Robolectric.application); View convertView = LayoutInflater.from(Robolectric.application).inflate(row_layout, null); ViewGroup row = (ViewGroup) adapter.getView(0, convertView, genericLayout); LinearLayout inputsLinearLayout = (LinearLayout) row.getChildAt(2); for (int i = 0; i < inputsLinearLayout.getChildCount(); i++) { View childView = inputsLinearLayout.getChildAt(i); if (childView instanceof EditText) { results.add((EditText) childView); } } return results; } }
Jeff, reordered Loss Reasons
app/src/test/java/org/clintonhealthaccess/lmis/app/adapters/LossesCommoditiesAdapterTest.java
Jeff, reordered Loss Reasons
Java
bsd-3-clause
5278fcddb0533d2ea42c095eec854b7966844bae
0
joansmith/basex,dimitarp/basex,JensErat/basex,deshmnnit04/basex,dimitarp/basex,drmacro/basex,vincentml/basex,drmacro/basex,dimitarp/basex,drmacro/basex,drmacro/basex,vincentml/basex,ksclarke/basex,ksclarke/basex,ksclarke/basex,drmacro/basex,joansmith/basex,ksclarke/basex,JensErat/basex,vincentml/basex,drmacro/basex,vincentml/basex,joansmith/basex,deshmnnit04/basex,BaseXdb/basex,BaseXdb/basex,deshmnnit04/basex,JensErat/basex,BaseXdb/basex,JensErat/basex,joansmith/basex,JensErat/basex,dimitarp/basex,dimitarp/basex,dimitarp/basex,joansmith/basex,BaseXdb/basex,vincentml/basex,vincentml/basex,dimitarp/basex,JensErat/basex,JensErat/basex,deshmnnit04/basex,BaseXdb/basex,drmacro/basex,ksclarke/basex,JensErat/basex,BaseXdb/basex,deshmnnit04/basex,dimitarp/basex,vincentml/basex,deshmnnit04/basex,joansmith/basex,deshmnnit04/basex,JensErat/basex,vincentml/basex,BaseXdb/basex,vincentml/basex,dimitarp/basex,BaseXdb/basex,joansmith/basex,joansmith/basex,ksclarke/basex,dimitarp/basex,deshmnnit04/basex,JensErat/basex,ksclarke/basex,vincentml/basex,joansmith/basex,deshmnnit04/basex,JensErat/basex,BaseXdb/basex,drmacro/basex,joansmith/basex,ksclarke/basex,BaseXdb/basex,ksclarke/basex,joansmith/basex,deshmnnit04/basex,drmacro/basex,drmacro/basex,dimitarp/basex,dimitarp/basex,JensErat/basex,joansmith/basex,drmacro/basex,ksclarke/basex,drmacro/basex,BaseXdb/basex,BaseXdb/basex,deshmnnit04/basex,deshmnnit04/basex,vincentml/basex,vincentml/basex,ksclarke/basex,ksclarke/basex
package org.basex.examples.server; import java.io.IOException; import java.util.Random; import org.basex.BaseXServer; import org.basex.server.ClientSession; import org.basex.util.Performance; import org.basex.util.Util; /** * This class performs a client/server stress tests with a specified * number of threads and queries. * * @author BaseX Team 2005-11, ISC License */ public final class ServerStressTest { /** Verbose flag. */ private static final boolean VERBOSE = false; /** Number of clients. */ private static final int NCLIENTS = 100; /** Number of runs per client. */ private static final int NQUERIES = 100; /** Input document. */ private static final String INPUT = "etc/xml/factbook.xml"; /** Query to be run ("%" serves as placeholder for dynamic content). */ private static final String QUERY = "(doc('test')//text())[position() = %]"; /** Server reference. */ static BaseXServer server; /** Random number generator. */ static final Random RND = new Random(); /** Result counter. */ static int counter; /** * Runs the example code. * @param args (ignored) command-line arguments * @throws Exception exception */ public static void main(final String[] args) throws Exception { System.out.println("=== ServerStressTest ==="); final Performance perf = new Performance(); // Run server instance System.out.println("\n* Start server."); server = new BaseXServer("-z"); // Create test database System.out.println("\n* Create test database."); final ClientSession cs = newSession(); cs.execute("create db test " + INPUT); System.out.print(cs.info()); cs.close(); // Run clients System.out.println("\n* Run " + NCLIENTS + " client threads."); final Client[] cl = new Client[NCLIENTS]; for(int i = 0; i < NCLIENTS; ++i) cl[i] = new Client(); for(final Client c : cl) c.start(); for(final Client c : cl) c.join(); stopServer(); System.out.println("\n* Time: " + perf); } /** * Stops the server. * @throws Exception exception */ static void stopServer() throws Exception { // Drop database and stop server System.out.println("\n* Stop server and drop test database."); final ClientSession cs = newSession(); try { cs.execute("drop db test"); } catch(final Exception ex) { System.out.println(cs.info()); ex.printStackTrace(); } cs.close(); server.stop(); } /** * Returns a session instance. * @return session * @throws IOException exception */ static ClientSession newSession() throws IOException { return new ClientSession("localhost", 1984, "admin", "admin"); } /** Single client. */ static final class Client extends Thread { /** Client session. */ private ClientSession session; /** * Default constructor. */ public Client() { try { session = newSession(); } catch(final IOException ex) { ex.printStackTrace(); } } @Override public void run() { try { // Perform some queries for(int i = 0; i < NQUERIES; ++i) { Performance.sleep((long) (50 * RND.nextDouble())); // Return nth text of the database final int n = (RND.nextInt() & 0xFF) + 1; final String qu = Util.info(QUERY, n); final String result = session.execute("xquery " + qu); if(VERBOSE) System.out.println("[" + counter++ + "] Thread " + getId() + ", Pos " + n + ": " + result); } session.close(); } catch(final Exception ex) { ex.printStackTrace(); } } } }
src/main/java/org/basex/examples/server/ServerStressTest.java
package org.basex.examples.server; import java.io.IOException; import java.util.Random; import org.basex.BaseXServer; import org.basex.server.ClientSession; import org.basex.util.Performance; import org.basex.util.Util; /** * This class performs a client/server stress tests with a specified * number of threads and queries. * * @author BaseX Team 2005-11, ISC License */ public final class ServerStressTest { /** Verbose flag. */ private static final boolean VERBOSE = false; /** Number of clients. */ private static final int NCLIENTS = 100; /** Number of runs per client. */ private static final int NQUERIES = 100; /** Input document. */ private static final String INPUT = "etc/xml/factbook.xml"; /** Query to be run ("%" serves as placeholder for dynamic content). */ private static final String QUERY = "(doc('test')//text())[position() = %]"; /** Server reference. */ static BaseXServer server; /** Random number generator. */ static final Random RND = new Random(); /** Result counter. */ static int counter; /** * Runs the example code. * @param args (ignored) command-line arguments * @throws Exception exception */ public static void main(final String[] args) throws Exception { System.out.println("=== Server StressTest ==="); final Performance perf = new Performance(); // Run server instance System.out.println("\n* Start server."); server = new BaseXServer("-z"); // Create test database System.out.println("\n* Create test database."); final ClientSession cs = newSession(); cs.execute("create db test " + INPUT); System.out.print(cs.info()); cs.close(); // Run clients System.out.println("\n* Run " + NCLIENTS + " client threads."); final Client[] cl = new Client[NCLIENTS]; for(int i = 0; i < NCLIENTS; ++i) cl[i] = new Client(); for(final Client c : cl) c.start(); for(final Client c : cl) c.join(); stopServer(); System.out.println("\n* Time: " + perf); } /** * Stops the server. * @throws Exception exception */ static void stopServer() throws Exception { // Drop database and stop server System.out.println("\n* Stop server and drop test database."); final ClientSession cs = newSession(); try { cs.execute("drop db test"); } catch(final Exception ex) { System.out.println(cs.info()); ex.printStackTrace(); } cs.close(); server.stop(); } /** * Returns a session instance. * @return session * @throws IOException exception */ static ClientSession newSession() throws IOException { return new ClientSession("localhost", 1984, "admin", "admin"); } /** Single client. */ static final class Client extends Thread { /** Client session. */ private ClientSession session; /** * Default constructor. */ public Client() { try { session = newSession(); } catch(final IOException ex) { ex.printStackTrace(); } } @Override public void run() { try { // Perform some queries for(int i = 0; i < NQUERIES; ++i) { Performance.sleep((long) (50 * RND.nextDouble())); // Return nth text of the database final int n = (RND.nextInt() & 0xFF) + 1; final String qu = Util.info(QUERY, n); final String result = session.execute("xquery " + qu); if(VERBOSE) System.out.println("[" + counter++ + "] Thread " + getId() + ", Pos " + n + ": " + result); } session.close(); } catch(final Exception ex) { ex.printStackTrace(); } } } }
[FIX] XQuery: relocation of LET clauses with non-deterministic expr. suppressed (e.g.: math:random(); flagged via Use.CTX)
src/main/java/org/basex/examples/server/ServerStressTest.java
[FIX] XQuery: relocation of LET clauses with non-deterministic expr. suppressed (e.g.: math:random(); flagged via Use.CTX)
Java
bsd-3-clause
a1b8485c6fa09ea6e313e82991985e5e643da350
0
Clashsoft/Dyvil,Clashsoft/Dyvil
package dyvil.tools.compiler.ast.statement; import dyvil.tools.compiler.ast.access.FieldAccess; import dyvil.tools.compiler.ast.context.IContext; import dyvil.tools.compiler.ast.expression.IValue; import dyvil.tools.compiler.ast.expression.LambdaExpr; import dyvil.tools.compiler.ast.generic.ITypeContext; import dyvil.tools.compiler.ast.method.IMethod; import dyvil.tools.compiler.ast.parameter.IParameter; import dyvil.tools.compiler.ast.parameter.MethodParameter; import dyvil.tools.compiler.ast.type.IType; import dyvil.tools.compiler.ast.type.Types; import dyvil.tools.parsing.Name; import dyvil.tools.parsing.marker.MarkerList; import dyvil.tools.parsing.position.ICodePosition; public class Closure extends StatementList { private boolean resolved; private IValue implicitValue; public Closure() { } public Closure(ICodePosition position) { this.position = position; } @Override public boolean isType(IType type) { return type.getFunctionalMethod() != null; } @Override public float getTypeMatch(IType type) { return this.isType(type) ? 1 : 0; } @Override public boolean isResolved() { return true; } @Override public IValue withType(IType type, ITypeContext typeContext, MarkerList markers, IContext context) { if (this.resolved) { return super.withType(type, typeContext, markers, context); } final IMethod functionalMethod = type.getFunctionalMethod(); if (functionalMethod == null) { return null; } final int parameterCount = functionalMethod.parameterCount(); final IParameter[] parameters = new IParameter[parameterCount]; for (int i = 0; i < parameterCount; i++) { parameters[i] = new MethodParameter(Name.getQualified("$" + i), Types.UNKNOWN); } if (type.isExtension() && parameterCount > 0) { this.implicitValue = new FieldAccess(parameters[0]); } final LambdaExpr lambdaExpr = new LambdaExpr(this.position, parameters, parameterCount); lambdaExpr.setValue(this); this.resolved = true; return lambdaExpr.withType(type, typeContext, markers, context); } @Override public IValue getImplicit() { return this.implicitValue; } @Override public IValue resolve(MarkerList markers, IContext context) { if (this.resolved) { this.returnType = null; return super.resolve(markers, context); } this.returnType = Types.UNKNOWN; // Do this in withType return this; } }
src/compiler/dyvil/tools/compiler/ast/statement/Closure.java
package dyvil.tools.compiler.ast.statement; import dyvil.tools.compiler.ast.context.IContext; import dyvil.tools.compiler.ast.expression.IValue; import dyvil.tools.compiler.ast.expression.LambdaExpr; import dyvil.tools.compiler.ast.generic.ITypeContext; import dyvil.tools.compiler.ast.method.IMethod; import dyvil.tools.compiler.ast.parameter.IParameter; import dyvil.tools.compiler.ast.parameter.MethodParameter; import dyvil.tools.compiler.ast.type.IType; import dyvil.tools.compiler.ast.type.Types; import dyvil.tools.parsing.Name; import dyvil.tools.parsing.marker.MarkerList; import dyvil.tools.parsing.position.ICodePosition; public class Closure extends StatementList { private boolean resolved; public Closure() { } public Closure(ICodePosition position) { this.position = position; } @Override public boolean isType(IType type) { return type.getFunctionalMethod() != null; } @Override public float getTypeMatch(IType type) { return this.isType(type) ? 1 : 0; } @Override public boolean isResolved() { return true; } @Override public IValue withType(IType type, ITypeContext typeContext, MarkerList markers, IContext context) { if (this.resolved) { return super.withType(type, typeContext, markers, context); } IMethod functionalMethod = type.getFunctionalMethod(); if (functionalMethod == null) { return null; } int parameterCount = functionalMethod.parameterCount(); IParameter[] parameters = new IParameter[parameterCount]; for (int i = 0; i < parameterCount; i++) { parameters[i] = new MethodParameter(Name.getQualified("$" + i), Types.UNKNOWN); } LambdaExpr lambdaExpr = new LambdaExpr(this.position, parameters, parameterCount); lambdaExpr.setValue(this); this.resolved = true; return lambdaExpr.withType(type, typeContext, markers, context); } @Override public IValue resolve(MarkerList markers, IContext context) { if (this.resolved) { this.returnType = null; return super.resolve(markers, context); } this.returnType = Types.UNKNOWN; // Do this in withType return this; } }
Implicit Closure Value - Closures in the context of an Extension Lambda Type now provide an implicit value pointing to the first parameter of the resulting Lambda Expression.
src/compiler/dyvil/tools/compiler/ast/statement/Closure.java
Implicit Closure Value
Java
bsd-3-clause
dc63ff7925795320cb7b7f5df8e48152abfcad9d
0
jesperpedersen/pgjdbc-ng,frode-carlsen/pgjdbc-ng,gregb/pgjdbc-ng,gregb/pgjdbc-ng,jesperpedersen/pgjdbc-ng,brettwooldridge/pgjdbc-ng
/** * Copyright (c) 2013, impossibl.com * 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 impossibl.com nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.impossibl.postgres.jdbc; import com.impossibl.postgres.api.jdbc.PGConnection; import com.impossibl.postgres.api.jdbc.PGNotificationListener; import com.impossibl.postgres.jdbc.Housekeeper.CleanupRunnable; import com.impossibl.postgres.jdbc.SQLTextTree.Node; import com.impossibl.postgres.jdbc.SQLTextTree.ParameterPiece; import com.impossibl.postgres.jdbc.SQLTextTree.Processor; import com.impossibl.postgres.protocol.Command; import com.impossibl.postgres.protocol.Protocol; import com.impossibl.postgres.protocol.QueryCommand; import com.impossibl.postgres.protocol.ResultField; import com.impossibl.postgres.protocol.ServerObjectType; import com.impossibl.postgres.system.BasicContext; import com.impossibl.postgres.system.NoticeException; import com.impossibl.postgres.types.ArrayType; import com.impossibl.postgres.types.CompositeType; import com.impossibl.postgres.types.Type; import com.impossibl.postgres.utils.BlockingReadTimeoutException; import static com.impossibl.postgres.jdbc.ErrorUtils.chainWarnings; import static com.impossibl.postgres.jdbc.ErrorUtils.makeSQLException; import static com.impossibl.postgres.jdbc.ErrorUtils.makeSQLWarningChain; import static com.impossibl.postgres.jdbc.Exceptions.CLOSED_CONNECTION; import static com.impossibl.postgres.jdbc.Exceptions.INVALID_COMMAND_FOR_GENERATED_KEYS; import static com.impossibl.postgres.jdbc.Exceptions.NOT_IMPLEMENTED; import static com.impossibl.postgres.jdbc.Exceptions.NOT_SUPPORTED; import static com.impossibl.postgres.jdbc.Exceptions.UNWRAP_ERROR; import static com.impossibl.postgres.jdbc.SQLTextUtils.appendReturningClause; import static com.impossibl.postgres.jdbc.SQLTextUtils.getBeginText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getCommitText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getGetSessionIsolationLevelText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getGetSessionReadabilityText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getIsolationLevel; import static com.impossibl.postgres.jdbc.SQLTextUtils.getReleaseSavepointText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getRollbackText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getRollbackToText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSavepointText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSessionIsolationLevelText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSessionReadabilityText; import static com.impossibl.postgres.jdbc.SQLTextUtils.isTrue; import static com.impossibl.postgres.jdbc.SQLTextUtils.prependCursorDeclaration; import static com.impossibl.postgres.protocol.TransactionStatus.Idle; import static com.impossibl.postgres.system.Settings.CONNECTION_READONLY; import static com.impossibl.postgres.system.Settings.PARSED_SQL_CACHE_SIZE; import static com.impossibl.postgres.system.Settings.PARSED_SQL_CACHE_SIZE_DEFAULT; import static com.impossibl.postgres.system.Settings.PREPARED_STATEMENT_CACHE_SIZE; import static com.impossibl.postgres.system.Settings.PREPARED_STATEMENT_CACHE_SIZE_DEFAULT; import java.io.IOException; import java.io.InterruptedIOException; import java.lang.ref.WeakReference; import java.net.SocketAddress; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLTimeoutException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Struct; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import static java.lang.Boolean.parseBoolean; import static java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT; import static java.sql.ResultSet.CONCUR_READ_ONLY; import static java.sql.ResultSet.TYPE_FORWARD_ONLY; import static java.sql.Statement.RETURN_GENERATED_KEYS; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableMap; import static java.util.concurrent.TimeUnit.SECONDS; /** * Connection implementation * @author <a href="mailto:kdubb@me.com">Kevin Wooten</a> * @author <a href="mailto:jesper.pedersen@redhat.com">Jesper Pedersen</a> */ public class PGConnectionImpl extends BasicContext implements PGConnection { /** * Cleans up server resources in the event of leaking connections * * @author kdubb * */ static class Cleanup implements CleanupRunnable { Protocol protocol; List<WeakReference<PGStatement>> statements; Housekeeper.Ref housekeeper; StackTraceElement[] allocationStackTrace; public Cleanup(Protocol protocol, List<WeakReference<PGStatement>> statements) { this.protocol = protocol; this.statements = statements; this.allocationStackTrace = new Exception().getStackTrace(); } @Override public String getKind() { return "connection"; } @Override public StackTraceElement[] getAllocationStackTrace() { return allocationStackTrace; } @Override public void run() { protocol.shutdown(); closeStatements(statements); housekeeper.release(); } } long statementId = 0L; long portalId = 0L; int savepointId; private int holdability; boolean autoCommit = true; int networkTimeout; SQLWarning warningChain; List<WeakReference<PGStatement>> activeStatements; Map<CachedStatementKey, CachedStatement> preparedStatementCache; final Housekeeper.Ref housekeeper; final Object cleanupKey; static Map<String, SQLText> parsedSqlCache; PGConnectionImpl(SocketAddress address, Properties settings, Housekeeper.Ref housekeeper) throws IOException, NoticeException { super(address, settings, Collections.<String, Class<?>>emptyMap()); this.activeStatements = new ArrayList<>(); final int statementCacheSize = getSetting(PREPARED_STATEMENT_CACHE_SIZE, PREPARED_STATEMENT_CACHE_SIZE_DEFAULT); if (statementCacheSize > 0) { preparedStatementCache = Collections.synchronizedMap(new LinkedHashMap<CachedStatementKey, CachedStatement>(statementCacheSize + 1, 1.1f, true) { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(Map.Entry<CachedStatementKey, CachedStatement> eldest) { if (size() > statementCacheSize) { try { PGStatement.dispose(PGConnectionImpl.this, ServerObjectType.Statement, eldest.getValue().name); } catch (SQLException e) { // Ignore... } return true; } else { return false; } } }); } final int sqlCacheSize = getSetting(PARSED_SQL_CACHE_SIZE, PARSED_SQL_CACHE_SIZE_DEFAULT); if (sqlCacheSize > 0) { synchronized (PGConnectionImpl.class) { if (parsedSqlCache == null) { parsedSqlCache = Collections.synchronizedMap(new LinkedHashMap<String, SQLText>(sqlCacheSize + 1, 1.1f, true) { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(Map.Entry<String, SQLText> eldest) { return size() > sqlCacheSize; } }); } } } this.housekeeper = housekeeper; if (this.housekeeper != null) this.cleanupKey = this.housekeeper.add(this, new Cleanup(protocol, activeStatements)); else this.cleanupKey = null; } @Override public void init() throws IOException, NoticeException { super.init(); applySettings(settings); } void applySettings(Properties settings) throws IOException { if (parseBoolean(settings.getProperty(CONNECTION_READONLY, "false"))) { try { setReadOnly(true); } catch (SQLException e) { throw new IOException(e); } } } /** * Add warning to end of warning chain * * @param warning */ public void addWarning(SQLWarning warning) { warningChain = chainWarnings(warningChain, warning); } /** * Ensure the connection is not closed * * @throws SQLException * If the connection is closed */ void checkClosed() throws SQLException { if (isClosed()) throw new SQLException("connection closed"); } /** * Ensures the connection is currently in manual-commit mode * * @throws SQLException * If the connection is not in manual-commit mode */ void checkManualCommit() throws SQLException { if (autoCommit) throw new SQLException("must not be in auto-commit mode"); } /** * Ensures the connection is currently in auto-commit mode * * @throws SQLException * IF the connection is not in auto-commit mode */ void checkAutoCommit() throws SQLException { if (autoCommit) throw new SQLException("must be in auto-commit mode"); } /** * Ensures that a transaction is active when in manual commit mode * * @throws SQLException */ void checkTransaction() throws SQLException { if (!autoCommit && protocol.getTransactionStatus() == Idle) { try { query(getBeginText()); } catch (IOException e) { throw new SQLException(e); } catch (NoticeException e) { throw makeSQLException(e.getNotice()); } } } /** * Generates and returns the next unique statement name for this connection * * @return New unique statement name */ String getNextStatementName() { return String.format("%016X", ++statementId); } /** * Generates and returns the next unique portal name for this connection * * @return New unique portal name */ String getNextPortalName() { return String.format("%016X", ++portalId); } /** * Called by statements to notify the connection of their closure * * @param statement */ void handleStatementClosure(PGStatement statement) { //Remove given & abandoned statements Iterator<WeakReference<PGStatement>> statementRefIter = activeStatements.iterator(); while (statementRefIter.hasNext()) { WeakReference<PGStatement> statementRef = statementRefIter.next(); if (statementRef.get() == null || statementRef.get() == statement) { statementRefIter.remove(); } } } /** * Closes the given list of result-sets * * @throws SQLException */ static void closeStatements(List<WeakReference<PGStatement>> statements) { for (WeakReference<PGStatement> statementRef : statements) { PGStatement statement = statementRef.get(); if (statement != null) { try { statement.internalClose(); } catch (SQLException e) { //Ignore... } } } } /** * Closes all active statements for this connection * * @throws SQLException */ void closeStatements() throws SQLException { closeStatements(activeStatements); } SQLText parseSQL(String sqlText) throws SQLException { try { if (parsedSqlCache == null) { return new SQLText(sqlText); } SQLText parsedSql = parsedSqlCache.get(sqlText); if (parsedSql == null) { parsedSql = new SQLText(sqlText); parsedSqlCache.put(sqlText, parsedSql); } return parsedSql.copy(); } catch (ParseException e) { throw new SQLException("Error parsing SQL at position " + e.getErrorOffset() + " (" + sqlText + ")"); } } /** * Executes the given command and throws a SQLException if an error was * encountered and returns a chain of SQLWarnings if any were generated. * * @param cmd * Command to execute * @return Chain of SQLWarning objects if any were encountered * @throws SQLException * If an error was encountered */ SQLWarning execute(Command cmd, boolean checkTxn) throws SQLException { if (checkTxn) { checkTransaction(); } //Enable network timeout long networkTimeoutMS = SECONDS.toMillis(networkTimeout); cmd.setNetworkTimeout(networkTimeoutMS); try { protocol.execute(cmd); if (cmd.getError() != null) { throw makeSQLException(cmd.getError()); } return makeSQLWarningChain(cmd.getWarnings()); } catch (BlockingReadTimeoutException e) { close(); throw new SQLTimeoutException(e); } catch (InterruptedIOException e) { close(); throw CLOSED_CONNECTION; } catch (IOException e) { throw new SQLException(e); } } /** * Executes the given SQL text ignoring all result values * * @param sql * SQL text to execute * @throws SQLException * If an error was encountered during execution */ void execute(String sql, boolean checkTxn) throws SQLException { if (checkTxn) { checkTransaction(); } try { query(sql); } catch (BlockingReadTimeoutException e) { close(); throw new SQLTimeoutException(e); } catch (InterruptedIOException e) { close(); throw CLOSED_CONNECTION; } catch (IOException e) { throw new SQLException(e); } catch (NoticeException e) { throw makeSQLException(e.getNotice()); } } /** * Executes the given SQL text returning the first column of the first row * * @param sql * SQL text to execute * @return String String value of the 1st column of the 1st row or empty * string if no results are available * @throws SQLException * If an error was encountered during execution */ String executeForString(String sql, boolean checkTxn) throws SQLException { if (checkTxn) { checkTransaction(); } try { return queryFirstResultString(sql); } catch (BlockingReadTimeoutException e) { close(); throw new SQLTimeoutException(e); } catch (InterruptedIOException e) { close(); throw CLOSED_CONNECTION; } catch (IOException e) { throw new SQLException(e); } catch (NoticeException e) { throw makeSQLException(e.getNotice()); } } QueryCommand.ResultBatch executeForFirstResultBatch(String sql, boolean checkTxn, Object... params) throws SQLException { if (checkTxn) { checkTransaction(); } try { return queryBatch(sql, Object[].class, params); } catch (BlockingReadTimeoutException e) { close(); throw new SQLTimeoutException(e); } catch (InterruptedIOException e) { close(); throw CLOSED_CONNECTION; } catch (IOException e) { throw new SQLException(e); } catch (NoticeException e) { throw makeSQLException(e.getNotice()); } } Object[] executeForFirstResult(String sql, boolean checkTxn, Object... params) throws SQLException { QueryCommand.ResultBatch resultBatch = executeForFirstResultBatch(sql, checkTxn, params); List<?> res = resultBatch.results; if (res == null || res.isEmpty()) return null; return (Object[]) res.get(0); } <T> T executeForFirstResultValue(String sql, boolean checkTxn, Class<T> returnType, Object... params) throws SQLException { Object[] result = executeForFirstResult(sql, checkTxn, params); if (result == null || result.length == 0) return null; return returnType.cast(result[0]); } long executeForRowsAffected(String sql, boolean checkTxn, Object... params) throws SQLException { QueryCommand.ResultBatch resultBatch = executeForFirstResultBatch(sql, checkTxn, params); return resultBatch.rowsAffected; } /** * Closes all statements and shuts down the protocol * * @throws SQLException If an error occurs closing any of the statements */ void internalClose() throws SQLException { closeStatements(); shutdown(); if (housekeeper != null) { housekeeper.remove(cleanupKey); housekeeper.release(); } } /** * {@inheritDoc} */ @Override public boolean isServerMinimumVersion(int major, int minor) { return getServerVersion().isMinimum(major, minor); } @Override public boolean isValid(int timeout) throws SQLException { //Not valid if connection is closed if (isClosed()) return false; return executeForString("SELECT '1'::char", false).equals("1"); } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { checkClosed(); return targetTypeMap; } @Override public void setTypeMap(Map<String, Class<?>> typeMap) throws SQLException { checkClosed(); targetTypeMap = unmodifiableMap(typeMap); } @Override public int getHoldability() throws SQLException { checkClosed(); return holdability; } @Override public void setHoldability(int holdability) throws SQLException { checkClosed(); if (holdability != ResultSet.CLOSE_CURSORS_AT_COMMIT && holdability != ResultSet.HOLD_CURSORS_OVER_COMMIT) { throw new SQLException("illegal argument"); } this.holdability = holdability; } @Override public DatabaseMetaData getMetaData() throws SQLException { checkClosed(); return new PGDatabaseMetaData(this); } @Override public boolean getAutoCommit() throws SQLException { checkClosed(); return autoCommit; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); // Do nothing if no change in state if (this.autoCommit == autoCommit) return; // Commit any in-flight transaction (cannot call commit as it will start a // new transaction since we would still be in manual commit mode) if (!this.autoCommit && protocol.getTransactionStatus() != Idle) { execute(getCommitText(), false); } this.autoCommit = autoCommit; } @Override public boolean isReadOnly() throws SQLException { checkClosed(); String readability = executeForString(getGetSessionReadabilityText(), false); return isTrue(readability); } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if (protocol.getTransactionStatus() != Idle) { throw new SQLException("cannot set read only during a transaction"); } execute(getSetSessionReadabilityText(readOnly), false); } @Override public int getTransactionIsolation() throws SQLException { checkClosed(); String isolLevel = executeForString(getGetSessionIsolationLevelText(), false); return getIsolationLevel(isolLevel); } @Override public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if (level != Connection.TRANSACTION_NONE && level != Connection.TRANSACTION_READ_UNCOMMITTED && level != Connection.TRANSACTION_READ_COMMITTED && level != Connection.TRANSACTION_REPEATABLE_READ && level != Connection.TRANSACTION_SERIALIZABLE) { throw new SQLException("illegal argument"); } execute(getSetSessionIsolationLevelText(level), false); } @Override public void commit() throws SQLException { checkClosed(); checkManualCommit(); // Commit the current transaction if (protocol.getTransactionStatus() != Idle) { execute(getCommitText(), false); } } @Override public void rollback() throws SQLException { checkClosed(); checkManualCommit(); // Roll back the current transaction if (protocol.getTransactionStatus() != Idle) { execute(getRollbackText(), false); } } @Override public Savepoint setSavepoint() throws SQLException { checkClosed(); checkManualCommit(); // Allocate new save-point name & wrapper PGSavepoint savepoint = new PGSavepoint(++savepointId); // Mark save-point execute(getSetSavepointText(savepoint), true); return savepoint; } @Override public Savepoint setSavepoint(String name) throws SQLException { checkClosed(); checkManualCommit(); // Allocate new save-point wrapper PGSavepoint savepoint = new PGSavepoint(name); // Mark save-point execute(getSetSavepointText(savepoint), true); return savepoint; } @Override public void rollback(Savepoint savepointParam) throws SQLException { checkClosed(); checkManualCommit(); PGSavepoint savepoint = (PGSavepoint) savepointParam; if (!savepoint.isValid()) { throw new SQLException("invalid savepoint"); } try { // Rollback to save-point (if in transaction) if (protocol.getTransactionStatus() != Idle) { execute(getRollbackToText(savepoint), false); } } finally { // Mark as released savepoint.setReleased(true); } } @Override public void releaseSavepoint(Savepoint savepointParam) throws SQLException { checkClosed(); checkManualCommit(); PGSavepoint savepoint = (PGSavepoint) savepointParam; if (!savepoint.isValid()) { throw new SQLException("invalid savepoint"); } try { // Release the save-point (if in a transaction) if (!savepoint.getReleased() && protocol.getTransactionStatus() != Idle) { execute(getReleaseSavepointText(savepoint), false); } } finally { // Use up the save-point savepoint.invalidate(); } } @Override public String getCatalog() throws SQLException { checkClosed(); return null; } @Override public void setCatalog(String catalog) throws SQLException { checkClosed(); } @Override public String getSchema() throws SQLException { checkClosed(); return null; } @Override public void setSchema(String schema) throws SQLException { checkClosed(); } @Override public String nativeSQL(String sql) throws SQLException { checkClosed(); SQLText sqlText = parseSQL(sql); SQLTextEscapes.processEscapes(sqlText, this); return sqlText.toString(); } @Override public PGStatement createStatement() throws SQLException { return createStatement(TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); } @Override public PGStatement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return createStatement(resultSetType, resultSetConcurrency, CLOSE_CURSORS_AT_COMMIT); } @Override public PGStatement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); PGSimpleStatement statement = new PGSimpleStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability); activeStatements.add(new WeakReference<PGStatement>(statement)); return statement; } @Override public PGPreparedStatement prepareStatement(String sql) throws SQLException { return prepareStatement(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); } @Override public PGPreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return prepareStatement(sql, resultSetType, resultSetConcurrency, CLOSE_CURSORS_AT_COMMIT); } @Override public PGPreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); SQLText sqlText = parseSQL(sql); return prepareStatement(sqlText, resultSetType, resultSetConcurrency, resultSetHoldability); } public PGPreparedStatement prepareStatement(SQLText sqlText, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { SQLTextEscapes.processEscapes(sqlText, this); String statementName = getNextStatementName(); String cursorName = null; if (resultSetType != ResultSet.TYPE_FORWARD_ONLY || resultSetConcurrency == ResultSet.CONCUR_UPDATABLE) { cursorName = "cursor" + statementName; if (!prependCursorDeclaration(sqlText, cursorName, resultSetType, resultSetHoldability, autoCommit)) { cursorName = null; } } final int[] parameterCount = new int[1]; sqlText.process(new Processor() { @Override public Node process(Node node) throws SQLException { if (node instanceof ParameterPiece) parameterCount[0] += 1; return node; } }, true); PGPreparedStatement statement = new PGPreparedStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability, statementName, sqlText.toString(), parameterCount[0], cursorName); activeStatements.add(new WeakReference<PGStatement>(statement)); return statement; } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { checkClosed(); SQLText sqlText = parseSQL(sql); if (autoGeneratedKeys != RETURN_GENERATED_KEYS) { return prepareStatement(sql); } if (!appendReturningClause(sqlText)) { throw INVALID_COMMAND_FOR_GENERATED_KEYS; } PGPreparedStatement statement = prepareStatement(sqlText, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); statement.setWantsGeneratedKeys(true); return statement; } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { checkClosed(); throw NOT_SUPPORTED; } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { checkClosed(); SQLText sqlText = parseSQL(sql); if (!appendReturningClause(sqlText, asList(columnNames))) { throw INVALID_COMMAND_FOR_GENERATED_KEYS; } PGPreparedStatement statement = prepareStatement(sqlText, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); statement.setWantsGeneratedKeys(true); return statement; } @Override public CallableStatement prepareCall(String sql) throws SQLException { return prepareCall(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return prepareCall(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, getHoldability()); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); SQLText sqlText = parseSQL(sql); return prepareCall(sqlText, resultSetType, resultSetConcurrency, resultSetHoldability); } public PGCallableStatement prepareCall(SQLText sqlText, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { final int[] parameterCount = new int[1]; Processor counter = new Processor() { @Override public Node process(Node node) throws SQLException { if (node instanceof ParameterPiece) parameterCount[0] += 1; return node; } }; sqlText.process(counter, true); int preParameterCount = parameterCount[0]; SQLTextEscapes.processEscapes(sqlText, this); parameterCount[0] = 0; sqlText.process(counter, true); int finalParameterCount = parameterCount[0]; String statementName = getNextStatementName(); String cursorName = null; if (resultSetType != ResultSet.TYPE_FORWARD_ONLY || resultSetConcurrency == ResultSet.CONCUR_UPDATABLE) { cursorName = "cursor" + statementName; if (!prependCursorDeclaration(sqlText, cursorName, resultSetType, resultSetHoldability, autoCommit)) { cursorName = null; } } boolean hasAssign = preParameterCount == (finalParameterCount + 1); PGCallableStatement statement = new PGCallableStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability, statementName, sqlText.toString(), parameterCount[0], cursorName, hasAssign); activeStatements.add(new WeakReference<PGStatement>(statement)); return statement; } @Override public Blob createBlob() throws SQLException { checkClosed(); int loOid = LargeObject.creat(this, 0); return new PGBlob(this, loOid); } @Override public Clob createClob() throws SQLException { checkClosed(); int loOid = LargeObject.creat(this, 0); return new PGClob(this, loOid); } @Override public SQLXML createSQLXML() throws SQLException { checkClosed(); return new PGSQLXML(this); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); Type type = getRegistry().loadType(typeName + "[]"); if (type == null) { throw new SQLException("Array type not found"); } return new PGArray(this, (ArrayType)type, elements); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkClosed(); Type type = getRegistry().loadType(typeName); if (!(type instanceof CompositeType)) { throw new SQLException("Invalid type for struct"); } return new PGStruct(this, (CompositeType)type, attributes); } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { // TODO: implement throw new UnsupportedOperationException(); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { // TODO: implement throw new UnsupportedOperationException(); } @Override public String getClientInfo(String name) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public Properties getClientInfo() throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public NClob createNClob() throws SQLException { checkClosed(); throw NOT_SUPPORTED; } @Override public boolean isClosed() throws SQLException { return !protocol.isConnected(); } @Override public void close() throws SQLException { // Ignore multiple closes if (isClosed()) return; internalClose(); } @Override public void abort(Executor executor) throws SQLException { getProtocol().abort(executor); shutdown(); if (housekeeper != null) housekeeper.remove(cleanupKey); } @Override public SQLWarning getWarnings() throws SQLException { checkClosed(); return warningChain; } @Override public void clearWarnings() throws SQLException { checkClosed(); warningChain = null; } @Override public int getNetworkTimeout() throws SQLException { checkClosed(); return networkTimeout; } @Override public void setNetworkTimeout(Executor executor, int networkTimeout) throws SQLException { checkClosed(); if (networkTimeout < 0) { throw new SQLException("invalid network timeout"); } this.networkTimeout = networkTimeout; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { if (!iface.isAssignableFrom(getClass())) { throw UNWRAP_ERROR; } return iface.cast(this); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isAssignableFrom(getClass()); } @Override public void addNotificationListener(String name, String channelNameFilter, PGNotificationListener listener) { super.addNotificationListener(name, channelNameFilter, listener); } @Override public void addNotificationListener(String channelNameFilter, PGNotificationListener listener) { super.addNotificationListener(null, channelNameFilter, listener); } @Override public void addNotificationListener(PGNotificationListener listener) { super.addNotificationListener(null, null, listener); } @Override public void removeNotificationListener(PGNotificationListener listener) { super.removeNotificationListener(listener); } CachedStatement getCachedStatement(CachedStatementKey key, Callable<CachedStatement> loader) throws Exception { if (preparedStatementCache == null) { return loader.call(); } CachedStatement cached = preparedStatementCache.get(key); if (cached == null) { cached = loader.call(); preparedStatementCache.put(key, cached); } return cached; } } class CachedStatementKey { String sql; List<Type> parameterTypes; public CachedStatementKey(String sql, List<Type> parameterTypes) { this.sql = sql; this.parameterTypes = parameterTypes; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((parameterTypes == null) ? 0 : parameterTypes.hashCode()); result = prime * result + ((sql == null) ? 0 : sql.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CachedStatementKey other = (CachedStatementKey) obj; if (parameterTypes == null) { if (other.parameterTypes != null) return false; } else if (!parameterTypes.equals(other.parameterTypes)) return false; if (sql == null) { if (other.sql != null) return false; } else if (!sql.equals(other.sql)) return false; return true; } } class CachedStatement { String name; List<Type> parameterTypes; List<ResultField> resultFields; public CachedStatement(String statementName, List<Type> parameterTypes, List<ResultField> resultFields) { this.name = statementName; this.parameterTypes = parameterTypes; this.resultFields = resultFields; } }
src/main/java/com/impossibl/postgres/jdbc/PGConnectionImpl.java
/** * Copyright (c) 2013, impossibl.com * 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 impossibl.com nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.impossibl.postgres.jdbc; import com.impossibl.postgres.api.jdbc.PGConnection; import com.impossibl.postgres.api.jdbc.PGNotificationListener; import com.impossibl.postgres.jdbc.Housekeeper.CleanupRunnable; import com.impossibl.postgres.jdbc.SQLTextTree.Node; import com.impossibl.postgres.jdbc.SQLTextTree.ParameterPiece; import com.impossibl.postgres.jdbc.SQLTextTree.Processor; import com.impossibl.postgres.protocol.Command; import com.impossibl.postgres.protocol.Protocol; import com.impossibl.postgres.protocol.QueryCommand; import com.impossibl.postgres.protocol.ResultField; import com.impossibl.postgres.protocol.ServerObjectType; import com.impossibl.postgres.system.BasicContext; import com.impossibl.postgres.system.NoticeException; import com.impossibl.postgres.types.ArrayType; import com.impossibl.postgres.types.CompositeType; import com.impossibl.postgres.types.Type; import com.impossibl.postgres.utils.BlockingReadTimeoutException; import static com.impossibl.postgres.jdbc.ErrorUtils.chainWarnings; import static com.impossibl.postgres.jdbc.ErrorUtils.makeSQLException; import static com.impossibl.postgres.jdbc.ErrorUtils.makeSQLWarningChain; import static com.impossibl.postgres.jdbc.Exceptions.CLOSED_CONNECTION; import static com.impossibl.postgres.jdbc.Exceptions.INVALID_COMMAND_FOR_GENERATED_KEYS; import static com.impossibl.postgres.jdbc.Exceptions.NOT_IMPLEMENTED; import static com.impossibl.postgres.jdbc.Exceptions.NOT_SUPPORTED; import static com.impossibl.postgres.jdbc.Exceptions.UNWRAP_ERROR; import static com.impossibl.postgres.jdbc.SQLTextUtils.appendReturningClause; import static com.impossibl.postgres.jdbc.SQLTextUtils.getBeginText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getCommitText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getGetSessionIsolationLevelText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getGetSessionReadabilityText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getIsolationLevel; import static com.impossibl.postgres.jdbc.SQLTextUtils.getReleaseSavepointText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getRollbackText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getRollbackToText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSavepointText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSessionIsolationLevelText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSessionReadabilityText; import static com.impossibl.postgres.jdbc.SQLTextUtils.isTrue; import static com.impossibl.postgres.jdbc.SQLTextUtils.prependCursorDeclaration; import static com.impossibl.postgres.protocol.TransactionStatus.Idle; import static com.impossibl.postgres.system.Settings.CONNECTION_READONLY; import static com.impossibl.postgres.system.Settings.PARSED_SQL_CACHE_SIZE; import static com.impossibl.postgres.system.Settings.PARSED_SQL_CACHE_SIZE_DEFAULT; import static com.impossibl.postgres.system.Settings.PREPARED_STATEMENT_CACHE_SIZE; import static com.impossibl.postgres.system.Settings.PREPARED_STATEMENT_CACHE_SIZE_DEFAULT; import java.io.IOException; import java.io.InterruptedIOException; import java.lang.ref.WeakReference; import java.net.SocketAddress; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLTimeoutException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Struct; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import static java.lang.Boolean.parseBoolean; import static java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT; import static java.sql.ResultSet.CONCUR_READ_ONLY; import static java.sql.ResultSet.TYPE_FORWARD_ONLY; import static java.sql.Statement.RETURN_GENERATED_KEYS; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableMap; import static java.util.concurrent.TimeUnit.SECONDS; /** * Connection implementation * @author <a href="mailto:kdubb@me.com">Kevin Wooten</a> * @author <a href="mailto:jesper.pedersen@redhat.com">Jesper Pedersen</a> */ public class PGConnectionImpl extends BasicContext implements PGConnection { /** * Cleans up server resources in the event of leaking connections * * @author kdubb * */ static class Cleanup implements CleanupRunnable { Protocol protocol; List<WeakReference<PGStatement>> statements; Housekeeper.Ref housekeeper; StackTraceElement[] allocationStackTrace; public Cleanup(Protocol protocol, List<WeakReference<PGStatement>> statements) { this.protocol = protocol; this.statements = statements; this.allocationStackTrace = new Exception().getStackTrace(); } @Override public String getKind() { return "connection"; } @Override public StackTraceElement[] getAllocationStackTrace() { return allocationStackTrace; } @Override public void run() { protocol.shutdown(); closeStatements(statements); housekeeper.release(); } } long statementId = 0L; long portalId = 0L; int savepointId; private int holdability; boolean autoCommit = true; int networkTimeout; SQLWarning warningChain; List<WeakReference<PGStatement>> activeStatements; Map<CachedStatementKey, CachedStatement> preparedStatementCache; final Housekeeper.Ref housekeeper; final Object cleanupKey; static Map<String, SQLText> parsedSqlCache; PGConnectionImpl(SocketAddress address, Properties settings, Housekeeper.Ref housekeeper) throws IOException, NoticeException { super(address, settings, Collections.<String, Class<?>>emptyMap()); this.activeStatements = new ArrayList<>(); final int statementCacheSize = getSetting(PREPARED_STATEMENT_CACHE_SIZE, PREPARED_STATEMENT_CACHE_SIZE_DEFAULT); if (statementCacheSize > 0) { preparedStatementCache = Collections.synchronizedMap(new LinkedHashMap<CachedStatementKey, CachedStatement>(statementCacheSize + 1, 1.1f, true) { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(Map.Entry<CachedStatementKey, CachedStatement> eldest) { if (size() > statementCacheSize) { try { PGStatement.dispose(PGConnectionImpl.this, ServerObjectType.Statement, eldest.getValue().name); } catch (SQLException e) { // Ignore... } return true; } else { return false; } } }); } final int sqlCacheSize = getSetting(PARSED_SQL_CACHE_SIZE, PARSED_SQL_CACHE_SIZE_DEFAULT); if (sqlCacheSize > 0) { synchronized (PGConnectionImpl.class) { if (parsedSqlCache == null) { parsedSqlCache = Collections.synchronizedMap(new LinkedHashMap<String, SQLText>(sqlCacheSize + 1, 1.1f, true) { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(Map.Entry<String, SQLText> eldest) { return size() > sqlCacheSize; } }); } } } this.housekeeper = housekeeper; if (this.housekeeper != null) this.cleanupKey = this.housekeeper.add(this, new Cleanup(protocol, activeStatements)); else this.cleanupKey = null; } @Override public void init() throws IOException, NoticeException { super.init(); applySettings(settings); } void applySettings(Properties settings) throws IOException { if (parseBoolean(settings.getProperty(CONNECTION_READONLY, "false"))) { try { setReadOnly(true); } catch (SQLException e) { throw new IOException(e); } } } /** * Add warning to end of warning chain * * @param warning */ public void addWarning(SQLWarning warning) { warningChain = chainWarnings(warningChain, warning); } /** * Ensure the connection is not closed * * @throws SQLException * If the connection is closed */ void checkClosed() throws SQLException { if (isClosed()) throw new SQLException("connection closed"); } /** * Ensures the connection is currently in manual-commit mode * * @throws SQLException * If the connection is not in manual-commit mode */ void checkManualCommit() throws SQLException { if (autoCommit) throw new SQLException("must not be in auto-commit mode"); } /** * Ensures the connection is currently in auto-commit mode * * @throws SQLException * IF the connection is not in auto-commit mode */ void checkAutoCommit() throws SQLException { if (autoCommit) throw new SQLException("must be in auto-commit mode"); } /** * Ensures that a transaction is active when in manual commit mode * * @throws SQLException */ void checkTransaction() throws SQLException { if (!autoCommit && protocol.getTransactionStatus() == Idle) { try { query(getBeginText()); } catch (IOException e) { throw new SQLException(e); } catch (NoticeException e) { throw makeSQLException(e.getNotice()); } } } /** * Generates and returns the next unique statement name for this connection * * @return New unique statement name */ String getNextStatementName() { return String.format("%016X", ++statementId); } /** * Generates and returns the next unique portal name for this connection * * @return New unique portal name */ String getNextPortalName() { return String.format("%016X", ++portalId); } /** * Called by statements to notify the connection of their closure * * @param statement */ void handleStatementClosure(PGStatement statement) { //Remove given & abandoned statements Iterator<WeakReference<PGStatement>> statementRefIter = activeStatements.iterator(); while (statementRefIter.hasNext()) { WeakReference<PGStatement> statementRef = statementRefIter.next(); if (statementRef.get() == null || statementRef.get() == statement) { statementRefIter.remove(); } } } /** * Closes the given list of result-sets * * @throws SQLException */ static void closeStatements(List<WeakReference<PGStatement>> statements) { for (WeakReference<PGStatement> statementRef : statements) { PGStatement statement = statementRef.get(); if (statement != null) { try { statement.internalClose(); } catch (SQLException e) { //Ignore... } } } } /** * Closes all active statements for this connection * * @throws SQLException */ void closeStatements() throws SQLException { closeStatements(activeStatements); } SQLText parseSQL(String sqlText) throws SQLException { try { if (parsedSqlCache == null) { return new SQLText(sqlText); } SQLText parsedSql = parsedSqlCache.get(sqlText); if (parsedSql == null) { parsedSql = new SQLText(sqlText); parsedSqlCache.put(sqlText, parsedSql); } return parsedSql.copy(); } catch (ParseException e) { throw new SQLException("Error parsing SQL at position " + e.getErrorOffset()); } } /** * Executes the given command and throws a SQLException if an error was * encountered and returns a chain of SQLWarnings if any were generated. * * @param cmd * Command to execute * @return Chain of SQLWarning objects if any were encountered * @throws SQLException * If an error was encountered */ SQLWarning execute(Command cmd, boolean checkTxn) throws SQLException { if (checkTxn) { checkTransaction(); } //Enable network timeout long networkTimeoutMS = SECONDS.toMillis(networkTimeout); cmd.setNetworkTimeout(networkTimeoutMS); try { protocol.execute(cmd); if (cmd.getError() != null) { throw makeSQLException(cmd.getError()); } return makeSQLWarningChain(cmd.getWarnings()); } catch (BlockingReadTimeoutException e) { close(); throw new SQLTimeoutException(e); } catch (InterruptedIOException e) { close(); throw CLOSED_CONNECTION; } catch (IOException e) { throw new SQLException(e); } } /** * Executes the given SQL text ignoring all result values * * @param sql * SQL text to execute * @throws SQLException * If an error was encountered during execution */ void execute(String sql, boolean checkTxn) throws SQLException { if (checkTxn) { checkTransaction(); } try { query(sql); } catch (BlockingReadTimeoutException e) { close(); throw new SQLTimeoutException(e); } catch (InterruptedIOException e) { close(); throw CLOSED_CONNECTION; } catch (IOException e) { throw new SQLException(e); } catch (NoticeException e) { throw makeSQLException(e.getNotice()); } } /** * Executes the given SQL text returning the first column of the first row * * @param sql * SQL text to execute * @return String String value of the 1st column of the 1st row or empty * string if no results are available * @throws SQLException * If an error was encountered during execution */ String executeForString(String sql, boolean checkTxn) throws SQLException { if (checkTxn) { checkTransaction(); } try { return queryFirstResultString(sql); } catch (BlockingReadTimeoutException e) { close(); throw new SQLTimeoutException(e); } catch (InterruptedIOException e) { close(); throw CLOSED_CONNECTION; } catch (IOException e) { throw new SQLException(e); } catch (NoticeException e) { throw makeSQLException(e.getNotice()); } } QueryCommand.ResultBatch executeForFirstResultBatch(String sql, boolean checkTxn, Object... params) throws SQLException { if (checkTxn) { checkTransaction(); } try { return queryBatch(sql, Object[].class, params); } catch (BlockingReadTimeoutException e) { close(); throw new SQLTimeoutException(e); } catch (InterruptedIOException e) { close(); throw CLOSED_CONNECTION; } catch (IOException e) { throw new SQLException(e); } catch (NoticeException e) { throw makeSQLException(e.getNotice()); } } Object[] executeForFirstResult(String sql, boolean checkTxn, Object... params) throws SQLException { QueryCommand.ResultBatch resultBatch = executeForFirstResultBatch(sql, checkTxn, params); List<?> res = resultBatch.results; if (res == null || res.isEmpty()) return null; return (Object[]) res.get(0); } <T> T executeForFirstResultValue(String sql, boolean checkTxn, Class<T> returnType, Object... params) throws SQLException { Object[] result = executeForFirstResult(sql, checkTxn, params); if (result == null || result.length == 0) return null; return returnType.cast(result[0]); } long executeForRowsAffected(String sql, boolean checkTxn, Object... params) throws SQLException { QueryCommand.ResultBatch resultBatch = executeForFirstResultBatch(sql, checkTxn, params); return resultBatch.rowsAffected; } /** * Closes all statements and shuts down the protocol * * @throws SQLException If an error occurs closing any of the statements */ void internalClose() throws SQLException { closeStatements(); shutdown(); if (housekeeper != null) { housekeeper.remove(cleanupKey); housekeeper.release(); } } /** * {@inheritDoc} */ @Override public boolean isServerMinimumVersion(int major, int minor) { return getServerVersion().isMinimum(major, minor); } @Override public boolean isValid(int timeout) throws SQLException { //Not valid if connection is closed if (isClosed()) return false; return executeForString("SELECT '1'::char", false).equals("1"); } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { checkClosed(); return targetTypeMap; } @Override public void setTypeMap(Map<String, Class<?>> typeMap) throws SQLException { checkClosed(); targetTypeMap = unmodifiableMap(typeMap); } @Override public int getHoldability() throws SQLException { checkClosed(); return holdability; } @Override public void setHoldability(int holdability) throws SQLException { checkClosed(); if (holdability != ResultSet.CLOSE_CURSORS_AT_COMMIT && holdability != ResultSet.HOLD_CURSORS_OVER_COMMIT) { throw new SQLException("illegal argument"); } this.holdability = holdability; } @Override public DatabaseMetaData getMetaData() throws SQLException { checkClosed(); return new PGDatabaseMetaData(this); } @Override public boolean getAutoCommit() throws SQLException { checkClosed(); return autoCommit; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); // Do nothing if no change in state if (this.autoCommit == autoCommit) return; // Commit any in-flight transaction (cannot call commit as it will start a // new transaction since we would still be in manual commit mode) if (!this.autoCommit && protocol.getTransactionStatus() != Idle) { execute(getCommitText(), false); } this.autoCommit = autoCommit; } @Override public boolean isReadOnly() throws SQLException { checkClosed(); String readability = executeForString(getGetSessionReadabilityText(), false); return isTrue(readability); } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if (protocol.getTransactionStatus() != Idle) { throw new SQLException("cannot set read only during a transaction"); } execute(getSetSessionReadabilityText(readOnly), false); } @Override public int getTransactionIsolation() throws SQLException { checkClosed(); String isolLevel = executeForString(getGetSessionIsolationLevelText(), false); return getIsolationLevel(isolLevel); } @Override public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if (level != Connection.TRANSACTION_NONE && level != Connection.TRANSACTION_READ_UNCOMMITTED && level != Connection.TRANSACTION_READ_COMMITTED && level != Connection.TRANSACTION_REPEATABLE_READ && level != Connection.TRANSACTION_SERIALIZABLE) { throw new SQLException("illegal argument"); } execute(getSetSessionIsolationLevelText(level), false); } @Override public void commit() throws SQLException { checkClosed(); checkManualCommit(); // Commit the current transaction if (protocol.getTransactionStatus() != Idle) { execute(getCommitText(), false); } } @Override public void rollback() throws SQLException { checkClosed(); checkManualCommit(); // Roll back the current transaction if (protocol.getTransactionStatus() != Idle) { execute(getRollbackText(), false); } } @Override public Savepoint setSavepoint() throws SQLException { checkClosed(); checkManualCommit(); // Allocate new save-point name & wrapper PGSavepoint savepoint = new PGSavepoint(++savepointId); // Mark save-point execute(getSetSavepointText(savepoint), true); return savepoint; } @Override public Savepoint setSavepoint(String name) throws SQLException { checkClosed(); checkManualCommit(); // Allocate new save-point wrapper PGSavepoint savepoint = new PGSavepoint(name); // Mark save-point execute(getSetSavepointText(savepoint), true); return savepoint; } @Override public void rollback(Savepoint savepointParam) throws SQLException { checkClosed(); checkManualCommit(); PGSavepoint savepoint = (PGSavepoint) savepointParam; if (!savepoint.isValid()) { throw new SQLException("invalid savepoint"); } try { // Rollback to save-point (if in transaction) if (protocol.getTransactionStatus() != Idle) { execute(getRollbackToText(savepoint), false); } } finally { // Mark as released savepoint.setReleased(true); } } @Override public void releaseSavepoint(Savepoint savepointParam) throws SQLException { checkClosed(); checkManualCommit(); PGSavepoint savepoint = (PGSavepoint) savepointParam; if (!savepoint.isValid()) { throw new SQLException("invalid savepoint"); } try { // Release the save-point (if in a transaction) if (!savepoint.getReleased() && protocol.getTransactionStatus() != Idle) { execute(getReleaseSavepointText(savepoint), false); } } finally { // Use up the save-point savepoint.invalidate(); } } @Override public String getCatalog() throws SQLException { checkClosed(); return null; } @Override public void setCatalog(String catalog) throws SQLException { checkClosed(); } @Override public String getSchema() throws SQLException { checkClosed(); return null; } @Override public void setSchema(String schema) throws SQLException { checkClosed(); } @Override public String nativeSQL(String sql) throws SQLException { checkClosed(); SQLText sqlText = parseSQL(sql); SQLTextEscapes.processEscapes(sqlText, this); return sqlText.toString(); } @Override public PGStatement createStatement() throws SQLException { return createStatement(TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); } @Override public PGStatement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return createStatement(resultSetType, resultSetConcurrency, CLOSE_CURSORS_AT_COMMIT); } @Override public PGStatement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); PGSimpleStatement statement = new PGSimpleStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability); activeStatements.add(new WeakReference<PGStatement>(statement)); return statement; } @Override public PGPreparedStatement prepareStatement(String sql) throws SQLException { return prepareStatement(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); } @Override public PGPreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return prepareStatement(sql, resultSetType, resultSetConcurrency, CLOSE_CURSORS_AT_COMMIT); } @Override public PGPreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); SQLText sqlText = parseSQL(sql); return prepareStatement(sqlText, resultSetType, resultSetConcurrency, resultSetHoldability); } public PGPreparedStatement prepareStatement(SQLText sqlText, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { SQLTextEscapes.processEscapes(sqlText, this); String statementName = getNextStatementName(); String cursorName = null; if (resultSetType != ResultSet.TYPE_FORWARD_ONLY || resultSetConcurrency == ResultSet.CONCUR_UPDATABLE) { cursorName = "cursor" + statementName; if (!prependCursorDeclaration(sqlText, cursorName, resultSetType, resultSetHoldability, autoCommit)) { cursorName = null; } } final int[] parameterCount = new int[1]; sqlText.process(new Processor() { @Override public Node process(Node node) throws SQLException { if (node instanceof ParameterPiece) parameterCount[0] += 1; return node; } }, true); PGPreparedStatement statement = new PGPreparedStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability, statementName, sqlText.toString(), parameterCount[0], cursorName); activeStatements.add(new WeakReference<PGStatement>(statement)); return statement; } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { checkClosed(); SQLText sqlText = parseSQL(sql); if (autoGeneratedKeys != RETURN_GENERATED_KEYS) { return prepareStatement(sql); } if (!appendReturningClause(sqlText)) { throw INVALID_COMMAND_FOR_GENERATED_KEYS; } PGPreparedStatement statement = prepareStatement(sqlText, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); statement.setWantsGeneratedKeys(true); return statement; } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { checkClosed(); throw NOT_SUPPORTED; } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { checkClosed(); SQLText sqlText = parseSQL(sql); if (!appendReturningClause(sqlText, asList(columnNames))) { throw INVALID_COMMAND_FOR_GENERATED_KEYS; } PGPreparedStatement statement = prepareStatement(sqlText, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); statement.setWantsGeneratedKeys(true); return statement; } @Override public CallableStatement prepareCall(String sql) throws SQLException { return prepareCall(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return prepareCall(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, getHoldability()); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); SQLText sqlText = parseSQL(sql); return prepareCall(sqlText, resultSetType, resultSetConcurrency, resultSetHoldability); } public PGCallableStatement prepareCall(SQLText sqlText, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { final int[] parameterCount = new int[1]; Processor counter = new Processor() { @Override public Node process(Node node) throws SQLException { if (node instanceof ParameterPiece) parameterCount[0] += 1; return node; } }; sqlText.process(counter, true); int preParameterCount = parameterCount[0]; SQLTextEscapes.processEscapes(sqlText, this); parameterCount[0] = 0; sqlText.process(counter, true); int finalParameterCount = parameterCount[0]; String statementName = getNextStatementName(); String cursorName = null; if (resultSetType != ResultSet.TYPE_FORWARD_ONLY || resultSetConcurrency == ResultSet.CONCUR_UPDATABLE) { cursorName = "cursor" + statementName; if (!prependCursorDeclaration(sqlText, cursorName, resultSetType, resultSetHoldability, autoCommit)) { cursorName = null; } } boolean hasAssign = preParameterCount == (finalParameterCount + 1); PGCallableStatement statement = new PGCallableStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability, statementName, sqlText.toString(), parameterCount[0], cursorName, hasAssign); activeStatements.add(new WeakReference<PGStatement>(statement)); return statement; } @Override public Blob createBlob() throws SQLException { checkClosed(); int loOid = LargeObject.creat(this, 0); return new PGBlob(this, loOid); } @Override public Clob createClob() throws SQLException { checkClosed(); int loOid = LargeObject.creat(this, 0); return new PGClob(this, loOid); } @Override public SQLXML createSQLXML() throws SQLException { checkClosed(); return new PGSQLXML(this); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); Type type = getRegistry().loadType(typeName + "[]"); if (type == null) { throw new SQLException("Array type not found"); } return new PGArray(this, (ArrayType)type, elements); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkClosed(); Type type = getRegistry().loadType(typeName); if (!(type instanceof CompositeType)) { throw new SQLException("Invalid type for struct"); } return new PGStruct(this, (CompositeType)type, attributes); } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { // TODO: implement throw new UnsupportedOperationException(); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { // TODO: implement throw new UnsupportedOperationException(); } @Override public String getClientInfo(String name) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public Properties getClientInfo() throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public NClob createNClob() throws SQLException { checkClosed(); throw NOT_SUPPORTED; } @Override public boolean isClosed() throws SQLException { return !protocol.isConnected(); } @Override public void close() throws SQLException { // Ignore multiple closes if (isClosed()) return; internalClose(); } @Override public void abort(Executor executor) throws SQLException { getProtocol().abort(executor); shutdown(); if (housekeeper != null) housekeeper.remove(cleanupKey); } @Override public SQLWarning getWarnings() throws SQLException { checkClosed(); return warningChain; } @Override public void clearWarnings() throws SQLException { checkClosed(); warningChain = null; } @Override public int getNetworkTimeout() throws SQLException { checkClosed(); return networkTimeout; } @Override public void setNetworkTimeout(Executor executor, int networkTimeout) throws SQLException { checkClosed(); if (networkTimeout < 0) { throw new SQLException("invalid network timeout"); } this.networkTimeout = networkTimeout; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { if (!iface.isAssignableFrom(getClass())) { throw UNWRAP_ERROR; } return iface.cast(this); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isAssignableFrom(getClass()); } @Override public void addNotificationListener(String name, String channelNameFilter, PGNotificationListener listener) { super.addNotificationListener(name, channelNameFilter, listener); } @Override public void addNotificationListener(String channelNameFilter, PGNotificationListener listener) { super.addNotificationListener(null, channelNameFilter, listener); } @Override public void addNotificationListener(PGNotificationListener listener) { super.addNotificationListener(null, null, listener); } @Override public void removeNotificationListener(PGNotificationListener listener) { super.removeNotificationListener(listener); } CachedStatement getCachedStatement(CachedStatementKey key, Callable<CachedStatement> loader) throws Exception { if (preparedStatementCache == null) { return loader.call(); } CachedStatement cached = preparedStatementCache.get(key); if (cached == null) { cached = loader.call(); preparedStatementCache.put(key, cached); } return cached; } } class CachedStatementKey { String sql; List<Type> parameterTypes; public CachedStatementKey(String sql, List<Type> parameterTypes) { this.sql = sql; this.parameterTypes = parameterTypes; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((parameterTypes == null) ? 0 : parameterTypes.hashCode()); result = prime * result + ((sql == null) ? 0 : sql.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CachedStatementKey other = (CachedStatementKey) obj; if (parameterTypes == null) { if (other.parameterTypes != null) return false; } else if (!parameterTypes.equals(other.parameterTypes)) return false; if (sql == null) { if (other.sql != null) return false; } else if (!sql.equals(other.sql)) return false; return true; } } class CachedStatement { String name; List<Type> parameterTypes; List<ResultField> resultFields; public CachedStatement(String statementName, List<Type> parameterTypes, List<ResultField> resultFields) { this.name = statementName; this.parameterTypes = parameterTypes; this.resultFields = resultFields; } }
More information for parsing exception
src/main/java/com/impossibl/postgres/jdbc/PGConnectionImpl.java
More information for parsing exception
Java
bsd-3-clause
949941c2f3166d1e7ca441be48a8e8a8b4effa41
0
QMXTech/MachineMusePowersuits,QMXTech/MachineMusePowersuits
package net.machinemuse.general.recipe; import cpw.mods.fml.common.registry.GameRegistry; import ic2.api.recipe.Recipes; import net.machinemuse.general.MuseLogger; import net.machinemuse.powersuits.common.ModCompatability; import net.machinemuse.powersuits.common.ModularPowersuits; import net.machinemuse.powersuits.item.ItemComponent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; public class RecipeManager { public static ItemStack copyAndResize(ItemStack stack, int number) { ItemStack copy = stack.copy(); copy.stackSize = number; return copy; } public static void addRecipes() { // Recipe ItemStack iron = new ItemStack(Item.ingotIron); ItemStack circuit = ItemComponent.wiring; ItemStack goldNugget = new ItemStack(Item.goldNugget); ItemStack ingotGold = new ItemStack(Item.ingotGold); ItemStack redstone = new ItemStack(Item.redstone); ItemStack wool = new ItemStack(Block.cloth); ItemStack string = new ItemStack(Item.silk); ItemStack paper = new ItemStack(Item.paper); ItemStack glass = new ItemStack(Block.glass); ItemStack glassPane = new ItemStack(Block.thinGlass); ItemStack glowstone = new ItemStack(Item.lightStoneDust); ItemStack emerald = new ItemStack(Item.emerald); ItemStack diamond = new ItemStack(Item.diamond); ItemStack lapis = new ItemStack(Item.dyePowder, 1, 4); ItemStack rosered = new ItemStack(Item.dyePowder, 1, 1); ItemStack cactusgreen = new ItemStack(Item.dyePowder, 1, 2); ItemStack enderPearl = new ItemStack(Item.enderPearl); ItemStack stone = new ItemStack(Block.stone); if (ModCompatability.vanillaRecipesEnabled()) { GameRegistry.addRecipe(ItemComponent.basicPlating, "II", "CI", "II", 'C', ItemComponent.wiring, 'I', iron); GameRegistry.addRecipe(ItemComponent.advancedPlating, "II", "CI", "II", 'C', ItemComponent.solenoid, 'I', diamond); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.controlCircuit, true, "WCI", "RGC", "IRW", 'W', ItemComponent.wiring, 'C', cactusgreen, 'I', ingotGold, 'G', glowstone, 'R', redstone)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(iron, 5), true, "P", 'P', ItemComponent.basicPlating)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(diamond, 5), true, "P", 'P', ItemComponent.advancedPlating)); GameRegistry.addRecipe(ItemComponent.laserHologram, "YTG", "TWT", "BTR", 'W', ItemComponent.wiring, 'T', glass, 'Y', glowstone, 'G', cactusgreen, 'B', lapis, 'R', rosered); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.tinkerTable), "ILI", "LEL", "ILI", 'I', iron, 'L', lapis, 'E', emerald); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.powerArmorHead), "III", "C C", 'I', iron, 'C', circuit); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.powerArmorTorso), "I I", "CIC", "III", 'I', iron, 'C', circuit); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.powerArmorLegs), "III", "C C", "I I", 'I', iron, 'C', circuit); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.powerArmorFeet), "C C", "I I", 'I', iron, 'C', circuit); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.powerTool), " C ", "CI ", " IC", 'I', iron, 'C', circuit); GameRegistry.addRecipe(copyAndResize(ItemComponent.wiring, 8), "GRG", 'G', goldNugget, 'R', redstone); GameRegistry.addRecipe(ItemComponent.parachute, "WWW", "S S", 'W', wool, 'S', string); GameRegistry.addRecipe(ItemComponent.lvcapacitor, "WPI", "W W", 'W', ItemComponent.wiring, 'I', iron, 'P', new ItemStack(Item.paper), 'L', lapis); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.mvcapacitor, "GPL", "W W", 'W', ItemComponent.wiring, 'G', goldNugget, 'P', new ItemStack(Item.paper), 'L', lapis)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.hvcapacitor, "EPG", "W W", 'W', ItemComponent.wiring, 'E', enderPearl, 'P', glass, 'G', glowstone)); GameRegistry.addRecipe(ItemComponent.solenoid, "WIW", "WIW", "WIW", 'W', ItemComponent.wiring, 'I', iron); GameRegistry.addRecipe(ItemComponent.gliderWing, " II", "II ", "I ", 'I', iron); GameRegistry.addRecipe(ItemComponent.servoMotor, " W ", "EIE", 'I', iron, 'E', ItemComponent.solenoid, 'W', ItemComponent.wiring); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.fieldEmitter, true, "SES", "ESE", "SES", 'S', ItemComponent.solenoid, 'E', enderPearl)); GameRegistry.addRecipe(ItemComponent.ionThruster, " FE", "IG ", "IFE", 'I', iron, 'E', ItemComponent.solenoid, 'G', glowstone, 'F', ItemComponent.fieldEmitter); } if (ModCompatability.UERecipesEnabled() && ModCompatability.isBasicComponentsLoaded()) { String basicCircuit = "circuitBasic"; String advancedCircuit = "circuitAdvanced"; String eliteCircuit = "circuitElite"; ItemStack lapisBlock = new ItemStack(Block.blockLapis); try { ItemStack steelIngot = OreDictionary.getOres("ingotSteel").get(0); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(steelIngot, 5), true, "P", 'P', ItemComponent.basicPlating)); } catch (Exception e) { MuseLogger.logError("Unable to load steel plate"); } GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.controlCircuit, true, "WC ", "RGC", " RW", 'W', ItemComponent.wiring, 'C', basicCircuit, 'G', glowstone, 'R', redstone)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.laserHologram, true, "YTG", "TWT", "BTR", 'W', ItemComponent.wiring, 'T', glass, 'Y', glowstone, 'G', cactusgreen, 'B', lapis, 'R', rosered)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.basicPlating, true, "II", "CI", "II", 'C', ItemComponent.wiring, 'I', "ingotSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.advancedPlating, true, "II", "CI", "II", 'C', "basicCircuit", 'I', diamond)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(diamond, 5), true, "P", 'P', ItemComponent.advancedPlating)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.tinkerTable), true, "ILI", "LEL", "ILI", 'I', "plateSteel", 'L', lapisBlock, 'E', emerald)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorHead), true, "III", "C C", 'I', "plateSteel", 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorTorso), true, "I I", "CIC", "III", 'I', "plateSteel", 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorLegs), true, "III", "C C", "I I", 'I', "plateSteel", 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorFeet), true, "C C", "I I", 'I', "plateSteel", 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerTool), true, " C ", "CI ", " IC", 'I', "plateSteel", 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(ItemComponent.wiring, 4), true, "GWG", 'G', goldNugget, 'W', "copperWire")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.parachute, true, "WWW", "S S", 'W', wool, 'S', string)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.lvcapacitor, "WBW", 'W', ItemComponent.wiring, 'B', "battery")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.mvcapacitor, "WBW", 'W', ItemComponent.wiring, 'B', "advancedBattery")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.hvcapacitor, "WBW", 'W', ItemComponent.wiring, 'B', "eliteBattery")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.solenoid, true, "WIW", "WIW", "WIW", 'W', ItemComponent.wiring, 'I', iron)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.gliderWing, true, " SI", "SI ", "S ", 'I', iron, 'S', "plateSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.servoMotor, true, " C ", "EIE", 'I', iron, 'E', ItemComponent.solenoid, 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.fieldEmitter, true, "SES", "ECE", "SES", 'S', ItemComponent.solenoid, 'E', enderPearl, 'C', "advancedCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.ionThruster, true, " FE", "CG ", "IFE", 'I', "plateSteel", 'E', ItemComponent.solenoid, 'G', glowstone, 'C', "advancedCircuit", 'F', ItemComponent.fieldEmitter)); } if (ModCompatability.IC2RecipesEnabled() && ModCompatability.isIndustrialCraftLoaded()) { circuit = ModCompatability.getIC2Item("electronicCircuit"); ItemStack advCircuit = ModCompatability.getIC2Item("advancedCircuit"); goldNugget = ModCompatability.getIC2Item("goldCableItem"); String refIron = "ingotRefinedIron"; String tin = "ingotTin"; String copper = "ingotCopper"; ItemStack reBattery = ModCompatability.getIC2Item("reBattery"); ItemStack fullBattery = ModCompatability.getIC2Item("chargedReBattery"); ItemStack energyCrystal = ModCompatability.getIC2Item("energyCrystal"); ItemStack lapotronCrystal = ModCompatability.getIC2Item("lapotronCrystal"); ItemStack iridiumOre = ModCompatability.getIC2Item("iridiumOre"); ItemStack carbonPlate = ModCompatability.getIC2Item("carbonPlate"); ItemStack machine = ModCompatability.getIC2Item("machine"); ItemStack advMachine = ModCompatability.getIC2Item("advancedMachine"); ItemStack gen = ModCompatability.getIC2Item("generator"); try { ItemStack refinedIron = OreDictionary.getOres("ingotRefinedIron").get(0); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(refinedIron, 5), true, "P", 'P', ItemComponent.basicPlating)); } catch (Exception e) { MuseLogger.logError("Unable to load Refined Iron"); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(iron, 5), true, "P", 'P', ItemComponent.basicPlating)); } GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.controlCircuit, true, "WC ", "RGC", " RW", 'W', ItemComponent.wiring, 'C', circuit, 'G', glowstone, 'R', redstone)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(diamond, 5), true, "P", 'P', ItemComponent.advancedPlating)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.laserHologram, true, "YTG", "TWT", "BTR", 'W', ItemComponent.wiring, 'T', glass, 'Y', glowstone, 'G', cactusgreen, 'B', lapis, 'R', rosered)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.basicPlating, true, "II", "CI", "II", 'C', circuit, 'I', "ingotRefinedIron")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.advancedPlating, true, "II", "CI", "II", 'C', advCircuit, 'I', diamond)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.tinkerTable), true, "E", "C", "M", 'E', emerald, 'C', circuit .copy(), 'M', machine)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorHead), true, "III", "C C", 'I', refIron, 'C', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorTorso), true, "I I", "CIC", "III", 'I', refIron, 'C', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorLegs), true, "III", "C C", "I I", 'I', refIron, 'C', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorFeet), true, "C C", "I I", 'I', refIron, 'C', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerTool), true, " C ", "CI ", " IC", 'I', refIron, 'C', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(ItemComponent.wiring, 2), true, "GRG", 'G', goldNugget.copy(), 'R', redstone)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.parachute, true, "WWW", "S S", 'W', wool, 'S', string)); Recipes.advRecipes.addRecipe(ItemComponent.lvcapacitor, "WBW", 'W', ItemComponent.wiring.copy(), 'B', reBattery); Recipes.advRecipes.addRecipe(ItemComponent.lvcapacitor, "WBW", 'W', ItemComponent.wiring.copy(), 'B', fullBattery); Recipes.advRecipes.addRecipe(ItemComponent.mvcapacitor, "WBW", 'W', ItemComponent.wiring.copy(), 'B', energyCrystal); Recipes.advRecipes.addRecipe(ItemComponent.hvcapacitor, "WBW", 'W', ItemComponent.wiring.copy(), 'B', lapotronCrystal); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.solenoid, true, " W ", "WIW", " W ", 'W', ItemComponent.wiring, 'I', machine)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.gliderWing, true, " CC", "CCI", "C ", 'C', carbonPlate.copy(), 'I', ItemComponent.solenoid)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.servoMotor, true, " W ", "EME", 'M', machine.copy(), 'E', ItemComponent.solenoid, 'W', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.fieldEmitter, true, "SES", "ECE", "SES", 'S', ItemComponent.solenoid, 'E', enderPearl, 'C', advCircuit)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.ionThruster, true, " FE", "MG ", "CFE", 'I', iron, 'E', ItemComponent.solenoid, 'F', ItemComponent.fieldEmitter, 'G', glowstone, 'C', advCircuit.copy(), 'M', advMachine.copy())); } if (ModCompatability.GregTechRecipesEnabled() && ModCompatability.isIndustrialCraftLoaded() && ModCompatability.isGregTechLoaded()) { // This means Gregtech is installed, and GregoriusT in his infinite // wisdom has registered literally everything in the universe with // the ore dictionary, so we can just use strings here :D ...once we // decide what to put. String computerMonitor = "craftingMonitorTier02"; String basicCircuit = "craftingCircuitTier02"; String advancedCircuit = "craftingCircuitTier04"; String dataStorageCircuit = "craftingCircuitTier05"; String energyFlowCircuit = "craftingCircuitTier07"; String machineParts = "craftingMachineParts"; String advancedMachine = "craftingRawMachineTier02"; String nitrogen = "molecule_1n"; String refinedIron = "ingotRefinedIron"; ItemStack neutronReflector = ModCompatability.getGregtechItem(40, 1, 0); String advancedHeatVent = "item.reactorVentDiamond"; ItemStack carbonPlate = ModCompatability.getIC2Item("carbonPlate"); ItemStack uninsulatedCopper = ModCompatability.getIC2Item("copperCableItem"); ItemStack luminator = ModCompatability.getIC2Item("luminator"); ItemStack reinforcedGlass = ModCompatability.getIC2Item("reinforcedGlass"); try { ItemStack titanium = OreDictionary.getOres("ingotSteel").get(0); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(titanium, 5), true, "P", 'P', ItemComponent.basicPlating)); } catch (Exception e) { MuseLogger.logError("Unable to load ingotSteel"); } try { ItemStack iridium = OreDictionary.getOres("ingotTitanium").get(0); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(iridium, 5), true, "P", 'P', ItemComponent.advancedPlating)); } catch (Exception e) { MuseLogger.logError("Unable to load ingotTitanium"); } GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.controlCircuit, true, "WCI", "RGC", "IRW", 'W', ItemComponent.wiring, 'C', advancedCircuit, 'G', energyFlowCircuit, 'R', dataStorageCircuit, 'I', "ingotElectrum")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.laserHologram, true, "LLL", "RGB", "LLL", 'L', luminator, 'R', "gemRuby", 'G', "gemGreenSapphire", 'B', "gemSapphire")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.basicPlating, true, "II", "CI", "II", 'C', basicCircuit, 'I', "ingotSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.advancedPlating, true, "II", "CI", "II", 'C', advancedCircuit, 'I', "ingotTitanium")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.tinkerTable), true, "CVC", "IEI", "IMI", 'C', advancedCircuit, 'E', emerald, 'V', computerMonitor, 'I', refinedIron, 'M', advancedMachine)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorHead), true, "ACA", "MVM", 'A', "ingotAluminium", 'C', dataStorageCircuit, 'M', machineParts, 'V', computerMonitor)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorTorso), true, "AMA", "ACA", "AAA", 'A', "ingotAluminium", 'C', dataStorageCircuit, 'M', machineParts)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorLegs), true, "MCM", "A A", "A A", 'A', "ingotAluminium", 'C', dataStorageCircuit, 'M', machineParts)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorFeet), true, "M M", "ACA", 'A', "ingotAluminium", 'C', dataStorageCircuit, 'M', machineParts)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerTool), true, "A A", "AMA", " C ", 'A', "ingotAluminium", 'C', dataStorageCircuit, 'M', machineParts)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(ItemComponent.wiring, 2), true, "CCC", "SSS", "CCC", 'C', uninsulatedCopper, 'S', "ingotSilver")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.parachute, true, "WWW", "S S", "CNC", 'W', wool, 'S', string, 'C', carbonPlate, 'N', nitrogen)); Recipes.advRecipes.addRecipe(ItemComponent.lvcapacitor, "IWI", "IBI", "IBI", 'W', ItemComponent.wiring, 'I', "ingotSteel", 'B', "crafting100kEUStore"); // Lithium battery Recipes.advRecipes.addRecipe(ItemComponent.mvcapacitor, "IWI", "IBI", "IBI", 'W', ItemComponent.wiring, 'I', "ingotTitanium", 'B', "crafting1kkEUStore"); // Lapotron crystal Recipes.advRecipes.addRecipe(ItemComponent.hvcapacitor, "IWI", "IBI", "IBI", 'W', ItemComponent.wiring, 'I', "ingotChrome", 'B', "crafting10kkEUStore"); // Lapotronic EnergyOrb GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.solenoid, true, "WSW", "WSW", "WSW", 'W', ItemComponent.wiring, 'S', "ingotSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.gliderWing, true, " MC", "MPI", "M ", 'P', carbonPlate, 'M', "plateMagnalium", 'I', ItemComponent.solenoid, 'C', advancedCircuit)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.servoMotor, true, "IBI", "CSC", "IBI", 'I', "ingotSteel", 'B', "ingotBrass", 'C', advancedCircuit, 'S', ItemComponent.solenoid)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.fieldEmitter, true, "ISI", "CUC", "ISI", 'I', "ingotTungstenSteel", 'S', ItemComponent.solenoid, 'U', energyFlowCircuit, 'C', "craftingSuperconductor")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.ionThruster, true, "ISI", "FCF", "N N", 'I', "plateAlloyIridium", 'S', "craftingSuperconductor", 'N', neutronReflector, 'C', ItemComponent.hvcapacitor, 'F', ItemComponent.fieldEmitter)); } if (ModCompatability.ThermalExpansionRecipesEnabled() && ModCompatability.isThermalExpansionLoaded()) { ItemStack pneumaticServo = ModCompatability.getThermexItem("pneumaticServo", 1); ItemStack machineFrame = ModCompatability.getThermexItem("machineFrame", 1); ItemStack powerCoilGold = ModCompatability.getThermexItem("powerCoilGold", 1); ItemStack powerCoilSilver = ModCompatability.getThermexItem("powerCoilSilver", 1); ItemStack powerCoilElectrum = ModCompatability.getThermexItem("powerCoilElectrum", 1); String gearCopper = "gearCopper"; String gearTin = "gearTin"; ItemStack gearInvar = ModCompatability.getThermexItem("gearInvar", 1); ItemStack compressedSawdust = ModCompatability.getThermexItem("hardenedGlass", 1); ItemStack energyFrameFull = ModCompatability.getThermexItem("energyCellFrameFull", 1); ItemStack conduitEnergy = ModCompatability.getThermexItem("energyConduitEmpty", 1); ItemStack teleportFrameFull = ModCompatability.getThermexItem("tesseractFrameFull", 1); // IC2ItemTest hardenedGlass = // ModCompatability.getThermexItem("blockGlass", 1); // Unmake the armor platings // try { // IC2ItemTest titanium = // OreDictionary.getOres("ingotTitanium").get(0); // GameRegistry.addRecipe(new // ShapedOreRecipe(copyAndResize(titanium, 5), true, // "P", 'P', ItemComponent.basicPlating)); // } catch (Exception e) { // MuseLogger.logError("Unable to load Titanium"); // } GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.controlCircuit, true, "EGW", "RWG", "WRE", 'E', "ingotElectrum", 'W', ItemComponent.wiring, 'G', glowstone, 'R', redstone)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.laserHologram, true, "RGB", " H ", "WLW", 'W', ItemComponent.wiring, 'L', powerCoilGold, 'H', glass, 'R', rosered, 'G', cactusgreen, 'B', lapis)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.basicPlating, true, "II", "CI", "II", 'C', gearTin, 'I', iron)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.advancedPlating, true, "II", "CI", "II", 'C', gearInvar, 'I', diamond)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.tinkerTable), true, " E ", "IMI", " R ", 'R', powerCoilSilver, 'M', machineFrame, 'E', emerald, 'I', "ingotElectrum")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorHead), true, "III", "W W", 'I', iron, 'W', ItemComponent.wiring)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorTorso), true, "I I", "WIW", "III", 'I', iron, 'W', ItemComponent.wiring)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorLegs), true, "III", "W W", "I I", 'I', iron, 'W', ItemComponent.wiring)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorFeet), true, "W W", "I I", 'I', iron, 'W', ItemComponent.wiring)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerTool), true, " I ", "IEI", " W ", 'W', ItemComponent.wiring, 'E', "ingotElectrum", 'I', iron)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(ItemComponent.wiring, 8), true, "CCC", "SSS", "CCC", 'C', "ingotCopper", 'S', "ingotSilver")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.parachute, true, "WWW", "S S", " O ", 'W', wool, 'S', string, 'O', pneumaticServo)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.lvcapacitor, false, "CPT", "W W", 'W', ItemComponent.wiring, 'C', "ingotSilver", 'T', "ingotGold", 'P', new ItemStack(Item.paper))); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.mvcapacitor, "WRW", 'W', ItemComponent.wiring, 'R', conduitEnergy)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.hvcapacitor, "WRW", 'W', ItemComponent.wiring, 'R', energyFrameFull)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.solenoid, true, "WSW", "WSW", "WSW", 'W', ItemComponent.wiring, 'S', iron)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.gliderWing, true, " GG", "GGI", "G ", 'G', compressedSawdust, 'I', ItemComponent.solenoid)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.servoMotor, true, " O ", "WSW", " O ", 'O', ItemComponent.solenoid, 'S', pneumaticServo, 'W', ItemComponent.wiring)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.fieldEmitter, true, " W ", "OUO", " W ", 'W', ItemComponent.wiring, 'O', ItemComponent.solenoid, 'U', teleportFrameFull)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.ionThruster, true, " FI", "IG ", "WFI", 'I', "ingotInvar", 'G', glowstone, 'W', ItemComponent.wiring, 'F', ItemComponent.fieldEmitter)); } } private void addShapedRecipe(ItemStack result, boolean mirror, String[] layout, String[] inputs) { Object[] recipe = new Object[1 + layout.length + inputs.length * 2]; recipe[0] = new Boolean(mirror); int i = 1; for (String line : layout) { recipe[i] = line; i++; } for (String line : inputs) { String[] p = line.split("="); if (p.length > 2) { MuseLogger.logError("Too many = signs at line " + line); } if (p[0].length() > 1) { MuseLogger.logError("More than one charspec at line " + line); } recipe[i] = p[0].charAt(0); recipe[i + 1] = parseItem(p[1]); i += 2; } GameRegistry.addRecipe(new ShapedOreRecipe(result, recipe)); } private Object parseItem(String itemIdentifier) { String[] p = itemIdentifier.split("\\."); String determinant = p[0].trim().toLowerCase(); if (p.length < 2) { MuseLogger.logError("Insufficiently defined item: " + itemIdentifier + " ; syntax is char=determinant.id or char=determinant.id.meta"); return null; } String identifier = p[1]; int meta = p.length > 2 ? parseInt(p[2]) : 0; if (meta == -1) { MuseLogger.logError("Invalid meta spec. Use decimal digits only please!"); return null; } if (determinant.equals("blockid")) { int blockID = parseInt(identifier); if (blockID < 0 || blockID > 4096) { MuseLogger.logError("Invalid block ID. Please use a decimal number between 0 and 4096."); return null; } Block block = Block.blocksList[blockID]; if (block == null) { MuseLogger.logError("Nothing registered at item ID " + blockID); return null; } return new ItemStack(block, meta, 1); } else if (determinant.equals("itemid")) { int itemID = parseInt(identifier); if (itemID < 0 || itemID > 32768) { MuseLogger.logError("Invalid item ID. Please use a decimal number between 0 and 32768."); return null; } Item item = Item.itemsList[itemID]; if (item == null) { MuseLogger.logError("Nothing registered at item ID " + itemID); return null; } return new ItemStack(item, meta, 1); } else if (determinant.equals("oredict")) { return identifier; } else if (determinant.equals("teitem")) { } else if (determinant.equals("blocksearch")) { // return doBlockSearch(identifier); } else if (determinant.equals("itemsearch")) { // return doItemSearch(identifier); } return null; } private int parseInt(String string) { try { return Integer.parseInt(string.trim()); } catch (NumberFormatException e) { return -1; } } }
src/minecraft/net/machinemuse/general/recipe/RecipeManager.java
package net.machinemuse.general.recipe; import cpw.mods.fml.common.registry.GameRegistry; import ic2.api.recipe.Recipes; import net.machinemuse.general.MuseLogger; import net.machinemuse.powersuits.common.ModCompatability; import net.machinemuse.powersuits.common.ModularPowersuits; import net.machinemuse.powersuits.item.ItemComponent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; public class RecipeManager { public static ItemStack copyAndResize(ItemStack stack, int number) { ItemStack copy = stack.copy(); copy.stackSize = number; return copy; } public static void addRecipes() { // Recipe ItemStack iron = new ItemStack(Item.ingotIron); ItemStack circuit = ItemComponent.wiring; ItemStack goldNugget = new ItemStack(Item.goldNugget); ItemStack ingotGold = new ItemStack(Item.ingotGold); ItemStack redstone = new ItemStack(Item.redstone); ItemStack wool = new ItemStack(Block.cloth); ItemStack string = new ItemStack(Item.silk); ItemStack paper = new ItemStack(Item.paper); ItemStack glass = new ItemStack(Block.glass); ItemStack glassPane = new ItemStack(Block.thinGlass); ItemStack glowstone = new ItemStack(Item.lightStoneDust); ItemStack emerald = new ItemStack(Item.emerald); ItemStack diamond = new ItemStack(Item.diamond); ItemStack lapis = new ItemStack(Item.dyePowder, 1, 4); ItemStack rosered = new ItemStack(Item.dyePowder, 1, 1); ItemStack cactusgreen = new ItemStack(Item.dyePowder, 1, 2); ItemStack enderPearl = new ItemStack(Item.enderPearl); ItemStack stone = new ItemStack(Block.stone); if (ModCompatability.vanillaRecipesEnabled()) { GameRegistry.addRecipe(ItemComponent.basicPlating, "II", "CI", "II", 'C', ItemComponent.wiring, 'I', iron); GameRegistry.addRecipe(ItemComponent.advancedPlating, "II", "CI", "II", 'C', ItemComponent.solenoid, 'I', diamond); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.controlCircuit, true, "WCI", "RGC", "IRW", 'W', ItemComponent.wiring, 'C', cactusgreen, 'I', ingotGold, 'G', glowstone, 'R', redstone)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(iron, 5), true, "P", 'P', ItemComponent.basicPlating)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(diamond, 5), true, "P", 'P', ItemComponent.advancedPlating)); GameRegistry.addRecipe(ItemComponent.laserHologram, "YTG", "TWT", "BTR", 'W', ItemComponent.wiring, 'T', glass, 'Y', glowstone, 'G', cactusgreen, 'B', lapis, 'R', rosered); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.tinkerTable), "ILI", "LEL", "ILI", 'I', iron, 'L', lapis, 'E', emerald); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.powerArmorHead), "III", "C C", 'I', iron, 'C', circuit); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.powerArmorTorso), "I I", "CIC", "III", 'I', iron, 'C', circuit); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.powerArmorLegs), "III", "C C", "I I", 'I', iron, 'C', circuit); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.powerArmorFeet), "C C", "I I", 'I', iron, 'C', circuit); GameRegistry.addRecipe(new ItemStack(ModularPowersuits.powerTool), " C ", "CI ", " IC", 'I', iron, 'C', circuit); GameRegistry.addRecipe(copyAndResize(ItemComponent.wiring, 8), "GRG", 'G', goldNugget, 'R', redstone); GameRegistry.addRecipe(ItemComponent.parachute, "WWW", "S S", 'W', wool, 'S', string); GameRegistry.addRecipe(ItemComponent.lvcapacitor, "WPI", "W W", 'W', ItemComponent.wiring, 'I', iron, 'P', new ItemStack(Item.paper), 'L', lapis); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.mvcapacitor, "GPL", "W W", 'W', ItemComponent.wiring, 'G', goldNugget, 'P', new ItemStack(Item.paper), 'L', lapis)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.hvcapacitor, "EPG", "W W", 'W', ItemComponent.wiring, 'E', enderPearl, 'P', glass, 'G', glowstone)); GameRegistry.addRecipe(ItemComponent.solenoid, "WIW", "WIW", "WIW", 'W', ItemComponent.wiring, 'I', iron); GameRegistry.addRecipe(ItemComponent.gliderWing, " II", "II ", "I ", 'I', iron); GameRegistry.addRecipe(ItemComponent.servoMotor, " W ", "EIE", 'I', iron, 'E', ItemComponent.solenoid, 'W', ItemComponent.wiring); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.fieldEmitter, true, "SES", "ESE", "SES", 'S', ItemComponent.solenoid, 'E', enderPearl)); GameRegistry.addRecipe(ItemComponent.ionThruster, " FE", "IG ", "IFE", 'I', iron, 'E', ItemComponent.solenoid, 'G', glowstone, 'F', ItemComponent.fieldEmitter); } if (ModCompatability.UERecipesEnabled() && ModCompatability.isBasicComponentsLoaded()) { String basicCircuit = "basicCircuit"; String advancedCircuit = "advancedCircuit"; String eliteCircuit = "eliteCircuit"; ItemStack lapisBlock = new ItemStack(Block.blockLapis); try { ItemStack steelIngot = OreDictionary.getOres("ingotSteel").get(0); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(steelIngot, 5), true, "P", 'P', ItemComponent.basicPlating)); } catch (Exception e) { MuseLogger.logError("Unable to load steel plate"); } GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.controlCircuit, true, "WC ", "RGC", " RW", 'W', ItemComponent.wiring, 'C', basicCircuit, 'G', glowstone, 'R', redstone)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.laserHologram, true, "YTG", "TWT", "BTR", 'W', ItemComponent.wiring, 'T', glass, 'Y', glowstone, 'G', cactusgreen, 'B', lapis, 'R', rosered)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.basicPlating, true, "II", "CI", "II", 'C', ItemComponent.wiring, 'I', "ingotSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.advancedPlating, true, "II", "CI", "II", 'C', "basicCircuit", 'I', diamond)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(diamond, 5), true, "P", 'P', ItemComponent.advancedPlating)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.tinkerTable), true, "ILI", "LEL", "ILI", 'I', "plateSteel", 'L', lapisBlock, 'E', emerald)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorHead), true, "III", "C C", 'I', "plateSteel", 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorTorso), true, "I I", "CIC", "III", 'I', "plateSteel", 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorLegs), true, "III", "C C", "I I", 'I', "plateSteel", 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorFeet), true, "C C", "I I", 'I', "plateSteel", 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerTool), true, " C ", "CI ", " IC", 'I', "plateSteel", 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(ItemComponent.wiring, 4), true, "GWG", 'G', goldNugget, 'W', "copperWire")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.parachute, true, "WWW", "S S", 'W', wool, 'S', string)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.lvcapacitor, "WBW", 'W', ItemComponent.wiring, 'B', "battery")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.mvcapacitor, "WBW", 'W', ItemComponent.wiring, 'B', "advancedBattery")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.hvcapacitor, "WBW", 'W', ItemComponent.wiring, 'B', "eliteBattery")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.solenoid, true, "WIW", "WIW", "WIW", 'W', ItemComponent.wiring, 'I', iron)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.gliderWing, true, " SI", "SI ", "S ", 'I', iron, 'S', "plateSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.servoMotor, true, " C ", "EIE", 'I', iron, 'E', ItemComponent.solenoid, 'C', "basicCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.fieldEmitter, true, "SES", "ECE", "SES", 'S', ItemComponent.solenoid, 'E', enderPearl, 'C', "advancedCircuit")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.ionThruster, true, " FE", "CG ", "IFE", 'I', "plateSteel", 'E', ItemComponent.solenoid, 'G', glowstone, 'C', "advancedCircuit", 'F', ItemComponent.fieldEmitter)); } if (ModCompatability.IC2RecipesEnabled() && ModCompatability.isIndustrialCraftLoaded()) { circuit = ModCompatability.getIC2Item("electronicCircuit"); ItemStack advCircuit = ModCompatability.getIC2Item("advancedCircuit"); goldNugget = ModCompatability.getIC2Item("goldCableItem"); String refIron = "ingotRefinedIron"; String tin = "ingotTin"; String copper = "ingotCopper"; ItemStack reBattery = ModCompatability.getIC2Item("reBattery"); ItemStack fullBattery = ModCompatability.getIC2Item("chargedReBattery"); ItemStack energyCrystal = ModCompatability.getIC2Item("energyCrystal"); ItemStack lapotronCrystal = ModCompatability.getIC2Item("lapotronCrystal"); ItemStack iridiumOre = ModCompatability.getIC2Item("iridiumOre"); ItemStack carbonPlate = ModCompatability.getIC2Item("carbonPlate"); ItemStack machine = ModCompatability.getIC2Item("machine"); ItemStack advMachine = ModCompatability.getIC2Item("advancedMachine"); ItemStack gen = ModCompatability.getIC2Item("generator"); try { ItemStack refinedIron = OreDictionary.getOres("ingotRefinedIron").get(0); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(refinedIron, 5), true, "P", 'P', ItemComponent.basicPlating)); } catch (Exception e) { MuseLogger.logError("Unable to load Refined Iron"); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(iron, 5), true, "P", 'P', ItemComponent.basicPlating)); } GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.controlCircuit, true, "WC ", "RGC", " RW", 'W', ItemComponent.wiring, 'C', circuit, 'G', glowstone, 'R', redstone)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(diamond, 5), true, "P", 'P', ItemComponent.advancedPlating)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.laserHologram, true, "YTG", "TWT", "BTR", 'W', ItemComponent.wiring, 'T', glass, 'Y', glowstone, 'G', cactusgreen, 'B', lapis, 'R', rosered)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.basicPlating, true, "II", "CI", "II", 'C', circuit, 'I', "ingotRefinedIron")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.advancedPlating, true, "II", "CI", "II", 'C', advCircuit, 'I', diamond)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.tinkerTable), true, "E", "C", "M", 'E', emerald, 'C', circuit .copy(), 'M', machine)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorHead), true, "III", "C C", 'I', refIron, 'C', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorTorso), true, "I I", "CIC", "III", 'I', refIron, 'C', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorLegs), true, "III", "C C", "I I", 'I', refIron, 'C', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorFeet), true, "C C", "I I", 'I', refIron, 'C', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerTool), true, " C ", "CI ", " IC", 'I', refIron, 'C', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(ItemComponent.wiring, 2), true, "GRG", 'G', goldNugget.copy(), 'R', redstone)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.parachute, true, "WWW", "S S", 'W', wool, 'S', string)); Recipes.advRecipes.addRecipe(ItemComponent.lvcapacitor, "WBW", 'W', ItemComponent.wiring.copy(), 'B', reBattery); Recipes.advRecipes.addRecipe(ItemComponent.lvcapacitor, "WBW", 'W', ItemComponent.wiring.copy(), 'B', fullBattery); Recipes.advRecipes.addRecipe(ItemComponent.mvcapacitor, "WBW", 'W', ItemComponent.wiring.copy(), 'B', energyCrystal); Recipes.advRecipes.addRecipe(ItemComponent.hvcapacitor, "WBW", 'W', ItemComponent.wiring.copy(), 'B', lapotronCrystal); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.solenoid, true, " W ", "WIW", " W ", 'W', ItemComponent.wiring, 'I', machine)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.gliderWing, true, " CC", "CCI", "C ", 'C', carbonPlate.copy(), 'I', ItemComponent.solenoid)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.servoMotor, true, " W ", "EME", 'M', machine.copy(), 'E', ItemComponent.solenoid, 'W', circuit.copy())); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.fieldEmitter, true, "SES", "ECE", "SES", 'S', ItemComponent.solenoid, 'E', enderPearl, 'C', advCircuit)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.ionThruster, true, " FE", "MG ", "CFE", 'I', iron, 'E', ItemComponent.solenoid, 'F', ItemComponent.fieldEmitter, 'G', glowstone, 'C', advCircuit.copy(), 'M', advMachine.copy())); } if (ModCompatability.GregTechRecipesEnabled() && ModCompatability.isIndustrialCraftLoaded() && ModCompatability.isGregTechLoaded()) { // This means Gregtech is installed, and GregoriusT in his infinite // wisdom has registered literally everything in the universe with // the ore dictionary, so we can just use strings here :D ...once we // decide what to put. String computerMonitor = "craftingMonitorTier02"; String basicCircuit = "craftingCircuitTier02"; String advancedCircuit = "craftingCircuitTier04"; String dataStorageCircuit = "craftingCircuitTier05"; String energyFlowCircuit = "craftingCircuitTier07"; String machineParts = "craftingMachineParts"; String advancedMachine = "craftingRawMachineTier02"; String nitrogen = "molecule_1n"; String refinedIron = "ingotRefinedIron"; ItemStack neutronReflector = ModCompatability.getGregtechItem(40, 1, 0); String advancedHeatVent = "item.reactorVentDiamond"; ItemStack carbonPlate = ModCompatability.getIC2Item("carbonPlate"); ItemStack uninsulatedCopper = ModCompatability.getIC2Item("copperCableItem"); ItemStack luminator = ModCompatability.getIC2Item("luminator"); ItemStack reinforcedGlass = ModCompatability.getIC2Item("reinforcedGlass"); try { ItemStack titanium = OreDictionary.getOres("ingotSteel").get(0); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(titanium, 5), true, "P", 'P', ItemComponent.basicPlating)); } catch (Exception e) { MuseLogger.logError("Unable to load ingotSteel"); } try { ItemStack iridium = OreDictionary.getOres("ingotTitanium").get(0); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(iridium, 5), true, "P", 'P', ItemComponent.advancedPlating)); } catch (Exception e) { MuseLogger.logError("Unable to load ingotTitanium"); } GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.controlCircuit, true, "WCI", "RGC", "IRW", 'W', ItemComponent.wiring, 'C', advancedCircuit, 'G', energyFlowCircuit, 'R', dataStorageCircuit, 'I', "ingotElectrum")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.laserHologram, true, "LLL", "RGB", "LLL", 'L', luminator, 'R', "gemRuby", 'G', "gemGreenSapphire", 'B', "gemSapphire")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.basicPlating, true, "II", "CI", "II", 'C', basicCircuit, 'I', "ingotSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.advancedPlating, true, "II", "CI", "II", 'C', advancedCircuit, 'I', "ingotTitanium")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.tinkerTable), true, "CVC", "IEI", "IMI", 'C', advancedCircuit, 'E', emerald, 'V', computerMonitor, 'I', refinedIron, 'M', advancedMachine)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorHead), true, "ACA", "MVM", 'A', "ingotAluminium", 'C', dataStorageCircuit, 'M', machineParts, 'V', computerMonitor)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorTorso), true, "AMA", "ACA", "AAA", 'A', "ingotAluminium", 'C', dataStorageCircuit, 'M', machineParts)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorLegs), true, "MCM", "A A", "A A", 'A', "ingotAluminium", 'C', dataStorageCircuit, 'M', machineParts)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorFeet), true, "M M", "ACA", 'A', "ingotAluminium", 'C', dataStorageCircuit, 'M', machineParts)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerTool), true, "A A", "AMA", " C ", 'A', "ingotAluminium", 'C', dataStorageCircuit, 'M', machineParts)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(ItemComponent.wiring, 2), true, "CCC", "SSS", "CCC", 'C', uninsulatedCopper, 'S', "ingotSilver")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.parachute, true, "WWW", "S S", "CNC", 'W', wool, 'S', string, 'C', carbonPlate, 'N', nitrogen)); Recipes.advRecipes.addRecipe(ItemComponent.lvcapacitor, "IWI", "IBI", "IBI", 'W', ItemComponent.wiring, 'I', "ingotSteel", 'B', "crafting100kEUStore"); // Lithium battery Recipes.advRecipes.addRecipe(ItemComponent.mvcapacitor, "IWI", "IBI", "IBI", 'W', ItemComponent.wiring, 'I', "ingotTitanium", 'B', "crafting1kkEUStore"); // Lapotron crystal Recipes.advRecipes.addRecipe(ItemComponent.hvcapacitor, "IWI", "IBI", "IBI", 'W', ItemComponent.wiring, 'I', "ingotChrome", 'B', "crafting10kkEUStore"); // Lapotronic EnergyOrb GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.solenoid, true, "WSW", "WSW", "WSW", 'W', ItemComponent.wiring, 'S', "ingotSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.gliderWing, true, " MC", "MPI", "M ", 'P', carbonPlate, 'M', "plateMagnalium", 'I', ItemComponent.solenoid, 'C', advancedCircuit)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.servoMotor, true, "IBI", "CSC", "IBI", 'I', "ingotSteel", 'B', "ingotBrass", 'C', advancedCircuit, 'S', ItemComponent.solenoid)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.fieldEmitter, true, "ISI", "CUC", "ISI", 'I', "ingotTungstenSteel", 'S', ItemComponent.solenoid, 'U', energyFlowCircuit, 'C', "craftingSuperconductor")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.ionThruster, true, "ISI", "FCF", "N N", 'I', "plateAlloyIridium", 'S', "craftingSuperconductor", 'N', neutronReflector, 'C', ItemComponent.hvcapacitor, 'F', ItemComponent.fieldEmitter)); } if (ModCompatability.ThermalExpansionRecipesEnabled() && ModCompatability.isThermalExpansionLoaded()) { ItemStack pneumaticServo = ModCompatability.getThermexItem("pneumaticServo", 1); ItemStack machineFrame = ModCompatability.getThermexItem("machineFrame", 1); ItemStack powerCoilGold = ModCompatability.getThermexItem("powerCoilGold", 1); ItemStack powerCoilSilver = ModCompatability.getThermexItem("powerCoilSilver", 1); ItemStack powerCoilElectrum = ModCompatability.getThermexItem("powerCoilElectrum", 1); String gearCopper = "gearCopper"; String gearTin = "gearTin"; ItemStack gearInvar = ModCompatability.getThermexItem("gearInvar", 1); ItemStack compressedSawdust = ModCompatability.getThermexItem("hardenedGlass", 1); ItemStack energyFrameFull = ModCompatability.getThermexItem("energyCellFrameFull", 1); ItemStack conduitEnergy = ModCompatability.getThermexItem("energyConduitEmpty", 1); ItemStack teleportFrameFull = ModCompatability.getThermexItem("tesseractFrameFull", 1); // IC2ItemTest hardenedGlass = // ModCompatability.getThermexItem("blockGlass", 1); // Unmake the armor platings // try { // IC2ItemTest titanium = // OreDictionary.getOres("ingotTitanium").get(0); // GameRegistry.addRecipe(new // ShapedOreRecipe(copyAndResize(titanium, 5), true, // "P", 'P', ItemComponent.basicPlating)); // } catch (Exception e) { // MuseLogger.logError("Unable to load Titanium"); // } GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.controlCircuit, true, "EGW", "RWG", "WRE", 'E', "ingotElectrum", 'W', ItemComponent.wiring, 'G', glowstone, 'R', redstone)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.laserHologram, true, "RGB", " H ", "WLW", 'W', ItemComponent.wiring, 'L', powerCoilGold, 'H', glass, 'R', rosered, 'G', cactusgreen, 'B', lapis)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.basicPlating, true, "II", "CI", "II", 'C', gearTin, 'I', iron)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.advancedPlating, true, "II", "CI", "II", 'C', gearInvar, 'I', diamond)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.tinkerTable), true, " E ", "IMI", " R ", 'R', powerCoilSilver, 'M', machineFrame, 'E', emerald, 'I', "ingotElectrum")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorHead), true, "III", "W W", 'I', iron, 'W', ItemComponent.wiring)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorTorso), true, "I I", "WIW", "III", 'I', iron, 'W', ItemComponent.wiring)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorLegs), true, "III", "W W", "I I", 'I', iron, 'W', ItemComponent.wiring)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerArmorFeet), true, "W W", "I I", 'I', iron, 'W', ItemComponent.wiring)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModularPowersuits.powerTool), true, " I ", "IEI", " W ", 'W', ItemComponent.wiring, 'E', "ingotElectrum", 'I', iron)); GameRegistry.addRecipe(new ShapedOreRecipe(copyAndResize(ItemComponent.wiring, 8), true, "CCC", "SSS", "CCC", 'C', "ingotCopper", 'S', "ingotSilver")); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.parachute, true, "WWW", "S S", " O ", 'W', wool, 'S', string, 'O', pneumaticServo)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.lvcapacitor, false, "CPT", "W W", 'W', ItemComponent.wiring, 'C', "ingotSilver", 'T', "ingotGold", 'P', new ItemStack(Item.paper))); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.mvcapacitor, "WRW", 'W', ItemComponent.wiring, 'R', conduitEnergy)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.hvcapacitor, "WRW", 'W', ItemComponent.wiring, 'R', energyFrameFull)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.solenoid, true, "WSW", "WSW", "WSW", 'W', ItemComponent.wiring, 'S', iron)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.gliderWing, true, " GG", "GGI", "G ", 'G', compressedSawdust, 'I', ItemComponent.solenoid)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.servoMotor, true, " O ", "WSW", " O ", 'O', ItemComponent.solenoid, 'S', pneumaticServo, 'W', ItemComponent.wiring)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.fieldEmitter, true, " W ", "OUO", " W ", 'W', ItemComponent.wiring, 'O', ItemComponent.solenoid, 'U', teleportFrameFull)); GameRegistry.addRecipe(new ShapedOreRecipe(ItemComponent.ionThruster, true, " FI", "IG ", "WFI", 'I', "ingotInvar", 'G', glowstone, 'W', ItemComponent.wiring, 'F', ItemComponent.fieldEmitter)); } } private void addShapedRecipe(ItemStack result, boolean mirror, String[] layout, String[] inputs) { Object[] recipe = new Object[1 + layout.length + inputs.length * 2]; recipe[0] = new Boolean(mirror); int i = 1; for (String line : layout) { recipe[i] = line; i++; } for (String line : inputs) { String[] p = line.split("="); if (p.length > 2) { MuseLogger.logError("Too many = signs at line " + line); } if (p[0].length() > 1) { MuseLogger.logError("More than one charspec at line " + line); } recipe[i] = p[0].charAt(0); recipe[i + 1] = parseItem(p[1]); i += 2; } GameRegistry.addRecipe(new ShapedOreRecipe(result, recipe)); } private Object parseItem(String itemIdentifier) { String[] p = itemIdentifier.split("\\."); String determinant = p[0].trim().toLowerCase(); if (p.length < 2) { MuseLogger.logError("Insufficiently defined item: " + itemIdentifier + " ; syntax is char=determinant.id or char=determinant.id.meta"); return null; } String identifier = p[1]; int meta = p.length > 2 ? parseInt(p[2]) : 0; if (meta == -1) { MuseLogger.logError("Invalid meta spec. Use decimal digits only please!"); return null; } if (determinant.equals("blockid")) { int blockID = parseInt(identifier); if (blockID < 0 || blockID > 4096) { MuseLogger.logError("Invalid block ID. Please use a decimal number between 0 and 4096."); return null; } Block block = Block.blocksList[blockID]; if (block == null) { MuseLogger.logError("Nothing registered at item ID " + blockID); return null; } return new ItemStack(block, meta, 1); } else if (determinant.equals("itemid")) { int itemID = parseInt(identifier); if (itemID < 0 || itemID > 32768) { MuseLogger.logError("Invalid item ID. Please use a decimal number between 0 and 32768."); return null; } Item item = Item.itemsList[itemID]; if (item == null) { MuseLogger.logError("Nothing registered at item ID " + itemID); return null; } return new ItemStack(item, meta, 1); } else if (determinant.equals("oredict")) { return identifier; } else if (determinant.equals("teitem")) { } else if (determinant.equals("blocksearch")) { // return doBlockSearch(identifier); } else if (determinant.equals("itemsearch")) { // return doItemSearch(identifier); } return null; } private int parseInt(String string) { try { return Integer.parseInt(string.trim()); } catch (NumberFormatException e) { return -1; } } }
Update RecipeManager.java more fixes
src/minecraft/net/machinemuse/general/recipe/RecipeManager.java
Update RecipeManager.java
Java
bsd-3-clause
e988810be08f44b833c451cd3e27cb2318ea1eda
0
dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
/* * Copyright (c) 2004-2019, University of Oslo * 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 HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.fileresource.internal; import android.content.Context; import android.util.Log; import android.webkit.MimeTypeMap; import androidx.annotation.NonNull; import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutor; import org.hisp.dhis.android.core.arch.call.D2Progress; import org.hisp.dhis.android.core.arch.call.internal.D2ProgressManager; import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder; import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableDataObjectStore; import org.hisp.dhis.android.core.arch.handlers.internal.HandlerWithTransformer; import org.hisp.dhis.android.core.arch.json.internal.ObjectMapperFactory; import org.hisp.dhis.android.core.common.State; import org.hisp.dhis.android.core.fileresource.FileResource; import org.hisp.dhis.android.core.maintenance.D2Error; import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValue; import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueTableInfo; import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValue; import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueTableInfo; import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeValueStore; import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityDataValueStore; import java.io.File; import java.io.IOException; import java.util.List; import javax.inject.Inject; import dagger.Reusable; import io.reactivex.Observable; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; @Reusable @SuppressWarnings("PMD.ExcessiveImports") public final class FileResourcePostCall { private final FileResourceService fileResourceService; private final APICallExecutor apiCallExecutor; private final TrackedEntityAttributeValueStore trackedEntityAttributeValueStore; private final TrackedEntityDataValueStore trackedEntityDataValueStore; private final IdentifiableDataObjectStore<FileResource> fileResourceStore; private final HandlerWithTransformer<FileResource> fileResourceHandler; private final Context context; @Inject FileResourcePostCall(@NonNull FileResourceService fileResourceService, @NonNull APICallExecutor apiCallExecutor, @NonNull TrackedEntityAttributeValueStore trackedEntityAttributeValueStore, @NonNull TrackedEntityDataValueStore trackedEntityDataValueStore, @NonNull IdentifiableDataObjectStore<FileResource> fileResourceStore, @NonNull HandlerWithTransformer<FileResource> fileResourceHandler, @NonNull Context context) { this.fileResourceService = fileResourceService; this.apiCallExecutor = apiCallExecutor; this.trackedEntityAttributeValueStore = trackedEntityAttributeValueStore; this.trackedEntityDataValueStore = trackedEntityDataValueStore; this.fileResourceStore = fileResourceStore; this.fileResourceHandler = fileResourceHandler; this.context = context; } public Observable<D2Progress> uploadFileResources(List<FileResource> filteredFileResources) { return Observable.defer(() -> { // if there is nothing to send, complete if (filteredFileResources.isEmpty()) { return Observable.empty(); } else { D2ProgressManager progressManager = new D2ProgressManager(filteredFileResources.size()); return Observable.create(emitter -> { for (FileResource fileResource : filteredFileResources) { File file = getRelatedFile(fileResource); ResponseBody responseBody = apiCallExecutor.executeObjectCall(fileResourceService.uploadFile(getFilePart(file))); handleResponse(responseBody.string(), fileResource, file); emitter.onNext(progressManager.increaseProgress(FileResource.class, true)); } emitter.onComplete(); }); } }); } private File getRelatedFile(FileResource fileResource) throws D2Error { return FileResourceUtil.getFile(context, fileResource); } private MultipartBody.Part getFilePart(File file) { String extension = MimeTypeMap.getFileExtensionFromUrl(file.getPath()); String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (type == null) { type = "image/*"; } return MultipartBody.Part .createFormData("file", file.getName(), RequestBody.create(MediaType.parse(type), file)); } private void handleResponse(String responseBody, FileResource fileResource, File file) { try { FileResource downloadedFileResource = getDownloadedFileResource(responseBody); updateValue(fileResource, downloadedFileResource); File downloadedFile = updateFile(file, downloadedFileResource, context); updateFileResource(fileResource, downloadedFileResource, downloadedFile); } catch (IOException e) { Log.v(FileResourcePostCall.class.getCanonicalName(), e.getMessage()); } } private FileResource getDownloadedFileResource(String responseBody) throws IOException { FileResourceResponse fileResourceResponse = ObjectMapperFactory.objectMapper().readValue(responseBody, FileResourceResponse.class); return fileResourceResponse.response().fileResource(); } private void updateValue(FileResource fileResource, FileResource downloadedFileResource) { if (!updateTrackedEntityAttributeValue(fileResource, downloadedFileResource)) { updateTrackedEntityDataValue(fileResource, downloadedFileResource); } } private boolean updateTrackedEntityAttributeValue(FileResource fileResource, FileResource downloadedFileResource) { String whereClause = new WhereClauseBuilder() .appendKeyStringValue(TrackedEntityAttributeValueTableInfo.Columns.VALUE, fileResource.uid()) .build(); TrackedEntityAttributeValue trackedEntityAttributeValue = trackedEntityAttributeValueStore.selectOneWhere(whereClause); if (trackedEntityAttributeValue == null) { return false; } else { trackedEntityAttributeValueStore.updateWhere(trackedEntityAttributeValue.toBuilder() .value(downloadedFileResource.uid()) .build()); return true; } } private void updateTrackedEntityDataValue(FileResource fileResource, FileResource downloadedFileResource) { String whereClause = new WhereClauseBuilder() .appendKeyStringValue(TrackedEntityDataValueTableInfo.Columns.VALUE, fileResource.uid()) .build(); TrackedEntityDataValue trackedEntityDataValue = trackedEntityDataValueStore.selectOneWhere(whereClause); if (trackedEntityDataValue != null) { trackedEntityDataValueStore.updateWhere(trackedEntityDataValue.toBuilder() .value(downloadedFileResource.uid()) .build()); } } private File updateFile(File file, FileResource fileResource, Context context) { return FileResourceUtil.renameFile(file, fileResource.uid(), context); } private void updateFileResource(FileResource fileResource, FileResource downloadedFileResource, File file) { fileResourceStore.delete(fileResource.uid()); fileResourceHandler.handle(downloadedFileResource.toBuilder() .state(State.SYNCED) .path(file.getAbsolutePath()) .build()); } }
core/src/main/java/org/hisp/dhis/android/core/fileresource/internal/FileResourcePostCall.java
/* * Copyright (c) 2004-2019, University of Oslo * 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 HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.fileresource.internal; import android.content.Context; import android.util.Log; import android.webkit.MimeTypeMap; import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutor; import org.hisp.dhis.android.core.arch.call.D2Progress; import org.hisp.dhis.android.core.arch.call.internal.D2ProgressManager; import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder; import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableDataObjectStore; import org.hisp.dhis.android.core.arch.handlers.internal.HandlerWithTransformer; import org.hisp.dhis.android.core.arch.json.internal.ObjectMapperFactory; import org.hisp.dhis.android.core.common.State; import org.hisp.dhis.android.core.fileresource.FileResource; import org.hisp.dhis.android.core.maintenance.D2Error; import org.hisp.dhis.android.core.systeminfo.SystemInfo; import org.hisp.dhis.android.core.systeminfo.internal.SystemInfoModuleDownloader; import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValue; import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueTableInfo; import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValue; import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueTableInfo; import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeValueStore; import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityDataValueStore; import java.io.File; import java.io.IOException; import java.util.List; import javax.inject.Inject; import androidx.annotation.NonNull; import dagger.Reusable; import io.reactivex.Observable; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; @Reusable @SuppressWarnings("PMD.ExcessiveImports") public final class FileResourcePostCall { private final FileResourceService fileResourceService; private final APICallExecutor apiCallExecutor; private final TrackedEntityAttributeValueStore trackedEntityAttributeValueStore; private final TrackedEntityDataValueStore trackedEntityDataValueStore; private final IdentifiableDataObjectStore<FileResource> fileResourceStore; private final HandlerWithTransformer<FileResource> fileResourceHandler; private final Context context; private final SystemInfoModuleDownloader systemInfoDownloader; @Inject FileResourcePostCall(@NonNull FileResourceService fileResourceService, @NonNull APICallExecutor apiCallExecutor, @NonNull TrackedEntityAttributeValueStore trackedEntityAttributeValueStore, @NonNull TrackedEntityDataValueStore trackedEntityDataValueStore, @NonNull IdentifiableDataObjectStore<FileResource> fileResourceStore, @NonNull HandlerWithTransformer<FileResource> fileResourceHandler, @NonNull Context context, @NonNull SystemInfoModuleDownloader systemInfoDownloader) { this.fileResourceService = fileResourceService; this.apiCallExecutor = apiCallExecutor; this.trackedEntityAttributeValueStore = trackedEntityAttributeValueStore; this.trackedEntityDataValueStore = trackedEntityDataValueStore; this.fileResourceStore = fileResourceStore; this.fileResourceHandler = fileResourceHandler; this.context = context; this.systemInfoDownloader = systemInfoDownloader; } public Observable<D2Progress> uploadFileResources(List<FileResource> filteredFileResources) { return Observable.defer(() -> { // if there is nothing to send, complete if (filteredFileResources.isEmpty()) { return Observable.empty(); } else { D2ProgressManager progressManager = new D2ProgressManager(filteredFileResources.size() + 1); return systemInfoDownloader.downloadMetadata().andThen(Observable.create(emitter -> { emitter.onNext(progressManager.increaseProgress(SystemInfo.class, false)); for (FileResource fileResource : filteredFileResources) { File file = getRelatedFile(fileResource); ResponseBody responseBody = apiCallExecutor.executeObjectCall(fileResourceService.uploadFile(getFilePart(file))); handleResponse(responseBody.string(), fileResource, file); emitter.onNext(progressManager.increaseProgress(FileResource.class, true)); } emitter.onComplete(); })); } }); } private File getRelatedFile(FileResource fileResource) throws D2Error { return FileResourceUtil.getFile(context, fileResource); } private MultipartBody.Part getFilePart(File file) { String extension = MimeTypeMap.getFileExtensionFromUrl(file.getPath()); String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (type == null) { type = "image/*"; } return MultipartBody.Part .createFormData("file", file.getName(), RequestBody.create(MediaType.parse(type), file)); } private void handleResponse(String responseBody, FileResource fileResource, File file) { try { FileResource downloadedFileResource = getDownloadedFileResource(responseBody); updateValue(fileResource, downloadedFileResource); File downloadedFile = updateFile(file, downloadedFileResource, context); updateFileResource(fileResource, downloadedFileResource, downloadedFile); } catch (IOException e) { Log.v(FileResourcePostCall.class.getCanonicalName(), e.getMessage()); } } private FileResource getDownloadedFileResource(String responseBody) throws IOException { FileResourceResponse fileResourceResponse = ObjectMapperFactory.objectMapper().readValue(responseBody, FileResourceResponse.class); return fileResourceResponse.response().fileResource(); } private void updateValue(FileResource fileResource, FileResource downloadedFileResource) { if (!updateTrackedEntityAttributeValue(fileResource, downloadedFileResource)) { updateTrackedEntityDataValue(fileResource, downloadedFileResource); } } private boolean updateTrackedEntityAttributeValue(FileResource fileResource, FileResource downloadedFileResource) { String whereClause = new WhereClauseBuilder() .appendKeyStringValue(TrackedEntityAttributeValueTableInfo.Columns.VALUE, fileResource.uid()) .build(); TrackedEntityAttributeValue trackedEntityAttributeValue = trackedEntityAttributeValueStore.selectOneWhere(whereClause); if (trackedEntityAttributeValue == null) { return false; } else { trackedEntityAttributeValueStore.updateWhere(trackedEntityAttributeValue.toBuilder() .value(downloadedFileResource.uid()) .build()); return true; } } private void updateTrackedEntityDataValue(FileResource fileResource, FileResource downloadedFileResource) { String whereClause = new WhereClauseBuilder() .appendKeyStringValue(TrackedEntityDataValueTableInfo.Columns.VALUE, fileResource.uid()) .build(); TrackedEntityDataValue trackedEntityDataValue = trackedEntityDataValueStore.selectOneWhere(whereClause); if (trackedEntityDataValue != null) { trackedEntityDataValueStore.updateWhere(trackedEntityDataValue.toBuilder() .value(downloadedFileResource.uid()) .build()); } } private File updateFile(File file, FileResource fileResource, Context context) { return FileResourceUtil.renameFile(file, fileResource.uid(), context); } private void updateFileResource(FileResource fileResource, FileResource downloadedFileResource, File file) { fileResourceStore.delete(fileResource.uid()); fileResourceHandler.handle(downloadedFileResource.toBuilder() .state(State.SYNCED) .path(file.getAbsolutePath()) .build()); } }
[ANDROSDK-1162-C] Remove system info call from FileResourcePostCall
core/src/main/java/org/hisp/dhis/android/core/fileresource/internal/FileResourcePostCall.java
[ANDROSDK-1162-C] Remove system info call from FileResourcePostCall
Java
bsd-3-clause
283c061e4c9e2ae0441e44cfd1b25d4a7a57c306
0
NCIP/common-security-module,NCIP/common-security-module,CBIIT/common-security-module,CBIIT/common-security-module,CBIIT/common-security-module,CBIIT/common-security-module,CBIIT/common-security-module,NCIP/common-security-module,NCIP/common-security-module
// AuthorizationDAOImplTest.java package test.gov.nih.nci.security.dao; import gov.nih.nci.security.SecurityServiceProvider; import gov.nih.nci.security.UserProvisioningManager; import gov.nih.nci.security.authorization.domainobjects.Group; import gov.nih.nci.security.authorization.domainobjects.Privilege; import gov.nih.nci.security.authorization.domainobjects.ProtectionElement; import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup; import gov.nih.nci.security.authorization.domainobjects.Role; import gov.nih.nci.security.authorization.domainobjects.User; import gov.nih.nci.security.dao.AuthorizationDAOImpl; import gov.nih.nci.security.exceptions.CSTransactionException; import java.util.Date; import junit.framework.TestCase; import junit.framework.TestSuite; /** * AuthorizationDAOImplTest (Copyright 2001 Your Company) * * <p> * This class performs unit tests on * gov.nih.nci.security.dao.AuthorizationDAOImpl * </p> * * <p> * Explanation about the tested class and its responsibilities * </p> * * <p> * Relations: AuthorizationDAOImpl extends java.lang.Object <br> * AuthorizationDAOImpl implements gov.nih.nci.security.dao.AuthorizationDAO * </p> * * @author Brian Husted * * @version $Revision: 1.11 $ * * @see gov.nih.nci.security.dao.AuthorizationDAOImpl * */ public class AuthorizationDAOImplTest extends TestCase { private static UserProvisioningManager upm; static { System.setProperty( "gov.nih.nci.security.configFile", "c:/temp/ApplicationSecurityConfig.xml" ); try{ upm = (UserProvisioningManager) SecurityServiceProvider .getUserProvisioningManager("Security"); }catch(Exception ex){ ex.printStackTrace(); } } /** * Constructor (needed for JTest) * * @param name * Name of Object */ public AuthorizationDAOImplTest(String name) { super(name); } /** * Used by JUnit (called before each test method) */ protected void setUp() { //authorizationdaoimpl = new AuthorizationDAOImpl(); } /** * Used by JUnit (called after each test method) */ protected void tearDown() { authorizationdaoimpl = null; } /** * Test the constructor: AuthorizationDAOImpl() */ public void testAuthorizationDAOImpl() { } /** * Test method: void finalize() finalize throws java.lang.Throwable */ public void testFinalize() { } /** * Test method: boolean checkPermission(AccessPermission, String) */ public void testCheckPermission_4() { //Must test for the following parameters! //AccessPermission; //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: boolean checkPermission(AccessPermission, User) */ public void testCheckPermission_3() { //Must test for the following parameters! //AccessPermission; //Must test for the following parameters! //User; } /** * Test method: boolean checkPermission(String, String, String) */ public void testCheckPermission_2() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: boolean checkPermission(String, String, String, String) */ public void testCheckPermission_1() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: boolean checkPermission(AccessPermission, Subject) */ public void testCheckPermission() { //Must test for the following parameters! //AccessPermission; //Must test for the following parameters! //Subject; } /** * Test method: [Ljava.security.Principal; [] getPrincipals(String) */ public void testGetPrincipals() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: gov.nih.nci.security.authorization.domainobjects.User * getUser(String) */ public void testGetUser() throws Exception { //Must test for the following parameters! } /** * Test method: * gov.nih.nci.security.authorization.domainobjects.ApplicationContext * getApplicationContext() */ public void testGetApplicationContext() { } /** * Test method: void assignProtectionElements(String, String[], String[]) */ public void testAssignProtectionElements_1() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } /** * Test method: void assignProtectionElements(String, String[]) */ public void testAssignProtectionElements() throws CSTransactionException { ProtectionGroup pg = createProtectionGroup(); ProtectionElement pe = createProtectionElement(); ProtectionElement pe2 = createProtectionElement(); upm.assignProtectionElements( pg.getProtectionGroupId().toString(), new String[]{ pe.getProtectionElementId().toString(), pe2.getProtectionElementId().toString() } ); } /** * Test method: void setOwnerForProtectionElement(String, String, String) */ public void testSetOwnerForProtectionElement() throws CSTransactionException { User u = createUser(); ProtectionElement pe = createProtectionElement(); //upm.setOwnerForProtectionElement( pe.getObjectId(), u.getLoginName() ); //upm.setOwnerForProtectionElement( pe.getObjectId(), u.getLoginName() ); } /** * Test method: void deAssignProtectionElements(String, String[], String[]) */ public void testDeAssignProtectionElements_1() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } /** * Test method: void deAssignProtectionElements(String[], String) */ public void testDeAssignProtectionElements() { //Must test for the following parameters! //String[]; //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } public void testCreateAndRemoveProtectionElement() throws CSTransactionException { ProtectionElement pe = createProtectionElement(); removeProtectionElement(pe); } /** * Test method: void createPrivilege(Privilege) */ protected ProtectionElement createProtectionElement() throws CSTransactionException { ProtectionElement pe = new ProtectionElement(); pe.setObjectId( "" + System.currentTimeMillis() ); pe.setProtectionElementDescription( "Test Desc"); pe.setProtectionElementName( "Test PE Name" + System.currentTimeMillis()); upm.createProtectionElement( pe ); System.out.println("Created PE with ID: " + pe.getProtectionElementId() ); return pe; } public void testAssignUserToGroup() throws CSTransactionException { User user = createUser(); Group group = createGroup(); System.out.println( "The Group name: " + group.getGroupName() ); upm.assignUserToGroup( user.getLoginName(), group.getGroupName() ); } private void removeProtectionElement(ProtectionElement pe) throws CSTransactionException { upm.removeProtectionElement(pe.getProtectionElementId().toString()); System.out.println("Deleted PE with ID: " + pe.getProtectionElementId()); } /** * Test method: * gov.nih.nci.security.authorization.domainobjects.ProtectionElement * getProtectionElement(String) */ public void testGetProtectionElement() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: * gov.nih.nci.security.authorization.domainobjects.ProtectionGroup * getProtectionGroup(String) */ public void testGetProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } public void testCreateAndRemoveProtectionGroup() throws CSTransactionException { ProtectionGroup g = createProtectionGroup(); removeProtectionGroup(g); } /** * Test method: void createPrivilege(Privilege) */ protected ProtectionGroup createProtectionGroup() throws CSTransactionException { ProtectionGroup g = new ProtectionGroup(); g.setProtectionGroupDescription("Test PG Desc"); g.setProtectionGroupName("Test PG Name" + System.currentTimeMillis()); upm.createProtectionGroup(g); System.out.println("Created Protection Group with ID: " + g.getProtectionGroupId()); return g; } private void removeProtectionGroup(ProtectionGroup g) throws CSTransactionException { upm.removeProtectionGroup(g.getProtectionGroupId().toString()); System.out.println("Deleted Protection Group with ID: " + g.getProtectionGroupId()); } /** * Test method: void modifyProtectionGroup(ProtectionGroup) */ public void testModifyProtectionGroup() { //Must test for the following parameters! //ProtectionGroup; } /** * Test method: void removeProtectionGroup(String) */ public void testRemoveProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void removeProtectionElement(ProtectionElement) */ public void testRemoveProtectionElement() { //Must test for the following parameters! //ProtectionElement; } /** * Test method: void assignUserRoleToProtectionGroup(String, String[], * String) */ public void testAssignUserRoleToProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } /** * Test method: void removeUserRoleFromProtectionGroup(String, String, * String[]) */ public void testRemoveUserRoleFromProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } public void testCreateAndRemoveRole() throws CSTransactionException { Role r = createRole(); removeRole(r); } /** * Test method: void createPrivilege(Privilege) */ protected Role createRole() throws CSTransactionException { Role r = new Role(); r.setDesc("Test Role Desc"); r.setName("Test Role Name" + System.currentTimeMillis()); upm.createRole(r); System.out.println("Created Role with ID: " + r.getId()); return r; } private void removeRole(Role r) throws CSTransactionException { upm.removeRole(r.getId().toString()); System.out.println("Deleted role with ID: " + r.getId()); } /** * Test method: void modifyRole(Role) */ public void testModifyRole() { //Must test for the following parameters! //Role; } public void testCreateAndRemovePrivilege() throws CSTransactionException { Privilege p = createPrivilege(); removePrivilege(p); } /** * Test method: void createPrivilege(Privilege) */ protected Privilege createPrivilege() throws CSTransactionException { Privilege p = new Privilege(); p.setDesc("Test Desc"); p.setName("Test Name" + System.currentTimeMillis()); upm.createPrivilege(p); System.out.println("Created Privilege with ID: " + p.getId()); return p; } private void removePrivilege(Privilege p) throws CSTransactionException { upm.removePrivilege(p.getId().toString()); System.out.println("Deleted privilege with ID: " + p.getId()); } /** * Test method: void modifyPrivilege(Privilege) */ public void testModifyPrivilege() { //Must test for the following parameters! //Privilege; } /** * Test method: void assignPrivilegesToRole(String[], String) */ public void testAssignPrivilegesToRole() { //Must test for the following parameters! //String[]; //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void removePrivilegesFromRole(String, String[]) */ public void testRemovePrivilegesFromRole() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } protected User createUser() throws CSTransactionException{ User u = new User(); u.setDepartment( "TestDept"); u.setEmailId( "test@test.gov"); u.setEndDate( new Date() ); u.setFirstName( "TestFirstName"); u.setLastName( "TestLastName"); u.setLoginName( "TestLoginName"+ System.currentTimeMillis()); u.setOrganization("TestOrg"); u.setPassword( "testPwd"); u.setLastName( "TestLastName"); u.setPhoneNumber( "TestPhone"); u.setStartDate( new Date() ); u.setTitle( "TestTitle"); upm.createUser( u ); return u; } public void testCreateAndRemoveGroup() throws CSTransactionException { Group g = createGroup(); removeGroup(g); } /** * Test method: void createPrivilege(Privilege) */ protected Group createGroup() throws CSTransactionException { Group g = new Group(); g.setGroupDesc("Test Desc"); g.setGroupName("Test Name" + System.currentTimeMillis()); upm.createGroup(g); System.out.println("Created group with ID: " + g.getGroupId()); return g; } private void removeGroup(Group g) throws CSTransactionException { upm.removeGroup(g.getGroupId().toString()); System.out.println("Deleted group with ID: " + g.getGroupId()); } /** * Test method: void removeGroup(String) */ public void testRemoveGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void modifyGroup(Group) */ public void testModifyGroup() { //Must test for the following parameters! //Group; } /** * Test method: void addUserToGroup(String, String) */ public void testAddUserToGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void removeUserFromGroup(String, String) */ public void testRemoveUserFromGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void assignGroupRoleToProtectionGroup(String, String, * String) */ public void testAssignGroupRoleToProtectionGroup() throws CSTransactionException { Group g = createGroup(); Role r = createRole(); Role r2 = createRole(); ProtectionGroup pg = createProtectionGroup(); upm.assignGroupRoleToProtectionGroup( pg.getProtectionGroupId() .toString(), g.getGroupId().toString(), new String[] { r.getId().toString(), r2.getId().toString() }); } /** * Test method: gov.nih.nci.security.authorization.domainobjects.Privilege * getPrivilege(String) */ public void testGetPrivilege() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void removeUserFromProtectionGroup(String, String) */ public void testRemoveUserFromProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void removeGroupRoleFromProtectionGroup(String, String, * String[]) */ public void testRemoveGroupRoleFromProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } /** * Test method: void removeGroupFromProtectionGroup(String, String) */ public void testRemoveGroupFromProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: gov.nih.nci.security.authorization.domainobjects.Role * getRole(String) */ public void testGetRole() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: java.util.Set getObjects(SearchCriteria) */ public void testGetObjects() { //Must test for the following parameters! //SearchCriteria; } /** * Main method needed to make a self runnable class * * @param args * This is required for main method */ public static void main(String[] args) { junit.textui.TestRunner.run(new TestSuite( AuthorizationDAOImplTest.class)); } private AuthorizationDAOImpl authorizationdaoimpl; }
api/src/test/gov/nih/nci/security/dao/AuthorizationDAOImplTest.java
// AuthorizationDAOImplTest.java package test.gov.nih.nci.security.dao; import gov.nih.nci.security.SecurityServiceProvider; import gov.nih.nci.security.UserProvisioningManager; import gov.nih.nci.security.authorization.domainobjects.Group; import gov.nih.nci.security.authorization.domainobjects.Privilege; import gov.nih.nci.security.authorization.domainobjects.ProtectionElement; import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup; import gov.nih.nci.security.authorization.domainobjects.Role; import gov.nih.nci.security.authorization.domainobjects.User; import gov.nih.nci.security.dao.AuthorizationDAOImpl; import gov.nih.nci.security.exceptions.CSTransactionException; import java.util.Date; import junit.framework.TestCase; import junit.framework.TestSuite; /** * AuthorizationDAOImplTest (Copyright 2001 Your Company) * * <p> * This class performs unit tests on * gov.nih.nci.security.dao.AuthorizationDAOImpl * </p> * * <p> * Explanation about the tested class and its responsibilities * </p> * * <p> * Relations: AuthorizationDAOImpl extends java.lang.Object <br> * AuthorizationDAOImpl implements gov.nih.nci.security.dao.AuthorizationDAO * </p> * * @author Brian Husted * * @version $Revision: 1.10 $ * * @see gov.nih.nci.security.dao.AuthorizationDAOImpl * */ public class AuthorizationDAOImplTest extends TestCase { private static UserProvisioningManager upm; static { try{ upm = (UserProvisioningManager) SecurityServiceProvider .getUserProvisioningManager("Security"); }catch(Exception ex){ ex.printStackTrace(); } } /** * Constructor (needed for JTest) * * @param name * Name of Object */ public AuthorizationDAOImplTest(String name) { super(name); } /** * Used by JUnit (called before each test method) */ protected void setUp() { //authorizationdaoimpl = new AuthorizationDAOImpl(); } /** * Used by JUnit (called after each test method) */ protected void tearDown() { authorizationdaoimpl = null; } /** * Test the constructor: AuthorizationDAOImpl() */ public void testAuthorizationDAOImpl() { } /** * Test method: void finalize() finalize throws java.lang.Throwable */ public void testFinalize() { } /** * Test method: boolean checkPermission(AccessPermission, String) */ public void testCheckPermission_4() { //Must test for the following parameters! //AccessPermission; //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: boolean checkPermission(AccessPermission, User) */ public void testCheckPermission_3() { //Must test for the following parameters! //AccessPermission; //Must test for the following parameters! //User; } /** * Test method: boolean checkPermission(String, String, String) */ public void testCheckPermission_2() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: boolean checkPermission(String, String, String, String) */ public void testCheckPermission_1() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: boolean checkPermission(AccessPermission, Subject) */ public void testCheckPermission() { //Must test for the following parameters! //AccessPermission; //Must test for the following parameters! //Subject; } /** * Test method: [Ljava.security.Principal; [] getPrincipals(String) */ public void testGetPrincipals() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: gov.nih.nci.security.authorization.domainobjects.User * getUser(String) */ public void testGetUser() throws Exception { //Must test for the following parameters! } /** * Test method: * gov.nih.nci.security.authorization.domainobjects.ApplicationContext * getApplicationContext() */ public void testGetApplicationContext() { } /** * Test method: void assignProtectionElements(String, String[], String[]) */ public void testAssignProtectionElements_1() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } /** * Test method: void assignProtectionElements(String, String[]) */ public void testAssignProtectionElements() throws CSTransactionException { ProtectionGroup pg = createProtectionGroup(); ProtectionElement pe = createProtectionElement(); ProtectionElement pe2 = createProtectionElement(); upm.assignProtectionElements( pg.getProtectionGroupId().toString(), new String[]{ pe.getProtectionElementId().toString(), pe2.getProtectionElementId().toString() } ); } /** * Test method: void setOwnerForProtectionElement(String, String, String) */ public void testSetOwnerForProtectionElement() throws CSTransactionException { User u = createUser(); ProtectionElement pe = createProtectionElement(); //upm.setOwnerForProtectionElement( pe.getObjectId(), u.getLoginName() ); //upm.setOwnerForProtectionElement( pe.getObjectId(), u.getLoginName() ); } /** * Test method: void deAssignProtectionElements(String, String[], String[]) */ public void testDeAssignProtectionElements_1() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } /** * Test method: void deAssignProtectionElements(String[], String) */ public void testDeAssignProtectionElements() { //Must test for the following parameters! //String[]; //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } public void testCreateAndRemoveProtectionElement() throws CSTransactionException { ProtectionElement pe = createProtectionElement(); removeProtectionElement(pe); } /** * Test method: void createPrivilege(Privilege) */ protected ProtectionElement createProtectionElement() throws CSTransactionException { ProtectionElement pe = new ProtectionElement(); pe.setObjectId( "" + System.currentTimeMillis() ); pe.setProtectionElementDescription( "Test Desc"); pe.setProtectionElementName( "Test PE Name" + System.currentTimeMillis()); upm.createProtectionElement( pe ); System.out.println("Created PE with ID: " + pe.getProtectionElementId() ); return pe; } private void removeProtectionElement(ProtectionElement pe) throws CSTransactionException { upm.removeProtectionElement(pe.getProtectionElementId().toString()); System.out.println("Deleted PE with ID: " + pe.getProtectionElementId()); } /** * Test method: * gov.nih.nci.security.authorization.domainobjects.ProtectionElement * getProtectionElement(String) */ public void testGetProtectionElement() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: * gov.nih.nci.security.authorization.domainobjects.ProtectionGroup * getProtectionGroup(String) */ public void testGetProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } public void testCreateAndRemoveProtectionGroup() throws CSTransactionException { ProtectionGroup g = createProtectionGroup(); removeProtectionGroup(g); } /** * Test method: void createPrivilege(Privilege) */ protected ProtectionGroup createProtectionGroup() throws CSTransactionException { ProtectionGroup g = new ProtectionGroup(); g.setProtectionGroupDescription("Test PG Desc"); g.setProtectionGroupName("Test PG Name" + System.currentTimeMillis()); upm.createProtectionGroup(g); System.out.println("Created Protection Group with ID: " + g.getProtectionGroupId()); return g; } private void removeProtectionGroup(ProtectionGroup g) throws CSTransactionException { upm.removeProtectionGroup(g.getProtectionGroupId().toString()); System.out.println("Deleted Protection Group with ID: " + g.getProtectionGroupId()); } /** * Test method: void modifyProtectionGroup(ProtectionGroup) */ public void testModifyProtectionGroup() { //Must test for the following parameters! //ProtectionGroup; } /** * Test method: void removeProtectionGroup(String) */ public void testRemoveProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void removeProtectionElement(ProtectionElement) */ public void testRemoveProtectionElement() { //Must test for the following parameters! //ProtectionElement; } /** * Test method: void assignUserRoleToProtectionGroup(String, String[], * String) */ public void testAssignUserRoleToProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } /** * Test method: void removeUserRoleFromProtectionGroup(String, String, * String[]) */ public void testRemoveUserRoleFromProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } public void testCreateAndRemoveRole() throws CSTransactionException { Role r = createRole(); removeRole(r); } /** * Test method: void createPrivilege(Privilege) */ protected Role createRole() throws CSTransactionException { Role r = new Role(); r.setDesc("Test Role Desc"); r.setName("Test Role Name" + System.currentTimeMillis()); upm.createRole(r); System.out.println("Created Role with ID: " + r.getId()); return r; } private void removeRole(Role r) throws CSTransactionException { upm.removeRole(r.getId().toString()); System.out.println("Deleted role with ID: " + r.getId()); } /** * Test method: void modifyRole(Role) */ public void testModifyRole() { //Must test for the following parameters! //Role; } public void testCreateAndRemovePrivilege() throws CSTransactionException { Privilege p = createPrivilege(); removePrivilege(p); } /** * Test method: void createPrivilege(Privilege) */ protected Privilege createPrivilege() throws CSTransactionException { Privilege p = new Privilege(); p.setDesc("Test Desc"); p.setName("Test Name" + System.currentTimeMillis()); upm.createPrivilege(p); System.out.println("Created Privilege with ID: " + p.getId()); return p; } private void removePrivilege(Privilege p) throws CSTransactionException { upm.removePrivilege(p.getId().toString()); System.out.println("Deleted privilege with ID: " + p.getId()); } /** * Test method: void modifyPrivilege(Privilege) */ public void testModifyPrivilege() { //Must test for the following parameters! //Privilege; } /** * Test method: void assignPrivilegesToRole(String[], String) */ public void testAssignPrivilegesToRole() { //Must test for the following parameters! //String[]; //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void removePrivilegesFromRole(String, String[]) */ public void testRemovePrivilegesFromRole() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } protected User createUser() throws CSTransactionException{ User u = new User(); u.setDepartment( "TestDept"); u.setEmailId( "test@test.gov"); u.setEndDate( new Date() ); u.setFirstName( "TestFirstName"); u.setLastName( "TestLastName"); u.setLoginName( "TestLoginName"+ System.currentTimeMillis()); u.setOrganization("TestOrg"); u.setPassword( "testPwd"); u.setLastName( "TestLastName"); u.setPhoneNumber( "TestPhone"); u.setStartDate( new Date() ); u.setTitle( "TestTitle"); upm.createUser( u ); return u; } public void testCreateAndRemoveGroup() throws CSTransactionException { Group g = createGroup(); removeGroup(g); } /** * Test method: void createPrivilege(Privilege) */ protected Group createGroup() throws CSTransactionException { Group g = new Group(); g.setGroupDesc("Test Desc"); g.setGroupName("Test Name" + System.currentTimeMillis()); upm.createGroup(g); System.out.println("Created group with ID: " + g.getGroupId()); return g; } private void removeGroup(Group g) throws CSTransactionException { upm.removeGroup(g.getGroupId().toString()); System.out.println("Deleted group with ID: " + g.getGroupId()); } /** * Test method: void removeGroup(String) */ public void testRemoveGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void modifyGroup(Group) */ public void testModifyGroup() { //Must test for the following parameters! //Group; } /** * Test method: void addUserToGroup(String, String) */ public void testAddUserToGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void removeUserFromGroup(String, String) */ public void testRemoveUserFromGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void assignGroupRoleToProtectionGroup(String, String, * String) */ public void testAssignGroupRoleToProtectionGroup() throws CSTransactionException { Group g = createGroup(); Role r = createRole(); Role r2 = createRole(); ProtectionGroup pg = createProtectionGroup(); upm.assignGroupRoleToProtectionGroup( pg.getProtectionGroupId() .toString(), g.getGroupId().toString(), new String[] { r.getId().toString(), r2.getId().toString() }); } /** * Test method: gov.nih.nci.security.authorization.domainobjects.Privilege * getPrivilege(String) */ public void testGetPrivilege() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void removeUserFromProtectionGroup(String, String) */ public void testRemoveUserFromProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: void removeGroupRoleFromProtectionGroup(String, String, * String[]) */ public void testRemoveGroupRoleFromProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; //Must test for the following parameters! //String[]; } /** * Test method: void removeGroupFromProtectionGroup(String, String) */ public void testRemoveGroupFromProtectionGroup() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: gov.nih.nci.security.authorization.domainobjects.Role * getRole(String) */ public void testGetRole() { //Must test for the following parameters! String str[] = { null, "\u0000", " " }; } /** * Test method: java.util.Set getObjects(SearchCriteria) */ public void testGetObjects() { //Must test for the following parameters! //SearchCriteria; } /** * Main method needed to make a self runnable class * * @param args * This is required for main method */ public static void main(String[] args) { junit.textui.TestRunner.run(new TestSuite( AuthorizationDAOImplTest.class)); } private AuthorizationDAOImpl authorizationdaoimpl; }
added unit test for testAssignUserToGroup SVN-Revision: 693
api/src/test/gov/nih/nci/security/dao/AuthorizationDAOImplTest.java
added unit test for testAssignUserToGroup
Java
apache-2.0
1e63411375a21c39ebca5c7640c87e01cb9b0b5d
0
opencb/hpg-pore,opencb/hpg-pore,opencb/hpg-pore
src/main/java/org/opencb/hadoop_pore/NativePoreSupport.java
package org.opencb.hadoop_pore; public class NativePoreSupport { public native String getFastqs(byte[] img); public native String getInfo(byte[] img); public native String getEvents(byte[] img, String source, int startTime, int endTime); }
Removes the file src/main/java/org/opencb/hadoop_pore/NativePoreSupport.java
src/main/java/org/opencb/hadoop_pore/NativePoreSupport.java
Removes the file src/main/java/org/opencb/hadoop_pore/NativePoreSupport.java
Java
mit
ea3a60ba692661a52b57f231bebafff02ba1166a
0
NyaaCat/NyaaCore,NyaaCat/nyaautils,NyaaCat/nyaautils
package cat.nyaa.utils; import cat.nyaa.utils.internationalizer.I16rItemName; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.BlockState; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BlockStateMeta; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; public final class Message { public final BaseComponent inner; public Message(String text) { inner = new TextComponent(text); } public Message append(String text) { inner.addExtra(text); return this; } public Message appendFormat(Internationalization i18n, String template, Object... obj) { return append(i18n.get(template, obj)); } public Message append(ItemStack item) { return append(item, "{itemName} *{amount}"); } public Message append(ItemStack item, String display) { item = item.clone(); boolean rawName = !(item.hasItemMeta() && item.getItemMeta().hasDisplayName()); BaseComponent nameComponent = rawName ? I16rItemName.getUnlocalizedName(item) : new TextComponent(item.getItemMeta().getDisplayName()); BaseComponent result; String itemJson = ""; if (item.hasItemMeta() && item.getItemMeta() instanceof BookMeta) { itemJson = ReflectionUtil.convertItemStackToJson(removeBookContent(item)); } else if (item.hasItemMeta() && item.getItemMeta() instanceof BlockStateMeta) { BlockStateMeta blockStateMeta = (BlockStateMeta) item.getItemMeta(); try { if (blockStateMeta.hasBlockState() && blockStateMeta.getBlockState() instanceof InventoryHolder) { InventoryHolder inventoryHolder = (InventoryHolder) blockStateMeta.getBlockState(); ArrayList<ItemStack> items = new ArrayList<>(); for (int i = 0; i < inventoryHolder.getInventory().getSize(); i++) { ItemStack itemStack = inventoryHolder.getInventory().getItem(i); if (itemStack != null && itemStack.getType() != Material.AIR) { if (items.size() < 5) { if (itemStack.hasItemMeta()) { if (itemStack.getItemMeta().hasLore()) { ItemMeta meta = itemStack.getItemMeta(); meta.setLore(new ArrayList<String>()); itemStack.setItemMeta(meta); } if (itemStack.getItemMeta() instanceof BookMeta) { itemStack = removeBookContent(itemStack); } } items.add(itemStack); } else { items.add(new ItemStack(Material.STONE)); } } } inventoryHolder.getInventory().clear(); for (int i = 0; i < items.size(); i++) { inventoryHolder.getInventory().setItem(i, items.get(i)); } blockStateMeta.setBlockState((BlockState) inventoryHolder); item.setItemMeta(blockStateMeta); itemJson = ReflectionUtil.convertItemStackToJson(item); } else { itemJson = ReflectionUtil.convertItemStackToJson(item); } } catch (IllegalStateException e) { itemJson = ReflectionUtil.convertItemStackToJson(item); } } else { itemJson = ReflectionUtil.convertItemStackToJson(item); } HoverEvent ev = new HoverEvent(HoverEvent.Action.SHOW_ITEM, new BaseComponent[]{new TextComponent(itemJson)}); nameComponent.setHoverEvent(ev); if ("{itemName}".equals(display)) { result = nameComponent; } else { String[] plain = display.split("\\{itemName\\}"); result = new TextComponent(plain[0]); result.setHoverEvent(ev); for (int i = 1; i < plain.length; i++) { result.addExtra(nameComponent); TextComponent tmp = new TextComponent(plain[i].replace("{amount}", Integer.toString(item.getAmount()))); tmp.setHoverEvent(ev); result.addExtra(tmp); } } result.setHoverEvent(ev); inner.addExtra(result); return this; } public Message append(BaseComponent component) { inner.addExtra(component); return this; } public Message send(Player p) { p.spigot().sendMessage(inner); return this; } public Message broadcast() { Bukkit.getServer().spigot().broadcast(inner); Bukkit.getConsoleSender().sendMessage(inner.toLegacyText()); return this; } public Message broadcast(String permission) { for (Player player : Bukkit.getOnlinePlayers()) { if (player.hasPermission(permission)) { this.send(player); } } return this; } public ItemStack removeBookContent(ItemStack item) { if (item.hasItemMeta() && item.getItemMeta() instanceof BookMeta) { ItemStack itemStack = item.clone(); BookMeta meta = (BookMeta) itemStack.getItemMeta(); meta.setPages(new ArrayList<String>()); itemStack.setItemMeta(meta); return itemStack; } return item; } }
src/main/java/cat/nyaa/utils/Message.java
package cat.nyaa.utils; import cat.nyaa.utils.internationalizer.I16rItemName; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.BlockState; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BlockStateMeta; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; public final class Message { public final BaseComponent inner; public Message(String text) { inner = new TextComponent(text); } public Message append(String text) { inner.addExtra(text); return this; } public Message appendFormat(Internationalization i18n, String template, Object... obj) { return append(i18n.get(template, obj)); } public Message append(ItemStack item) { return append(item, "{itemName} *{amount}"); } public Message append(ItemStack item, String display) { item = item.clone(); boolean rawName = !(item.hasItemMeta() && item.getItemMeta().hasDisplayName()); BaseComponent nameComponent = rawName ? I16rItemName.getUnlocalizedName(item) : new TextComponent(item.getItemMeta().getDisplayName()); BaseComponent result; String itemJson = ""; if (item.hasItemMeta() && item.getItemMeta() instanceof BookMeta) { itemJson = ReflectionUtil.convertItemStackToJson(removeBookContent(item)); } else if (item.hasItemMeta() && item.getItemMeta() instanceof BlockStateMeta) { BlockStateMeta blockStateMeta = (BlockStateMeta) item.getItemMeta(); try { if (blockStateMeta.hasBlockState() && blockStateMeta.getBlockState() instanceof InventoryHolder) { InventoryHolder inventoryHolder = (InventoryHolder) blockStateMeta.getBlockState(); ArrayList<ItemStack> items = new ArrayList<>(); for (int i = 0; i < inventoryHolder.getInventory().getSize(); i++) { ItemStack itemStack = inventoryHolder.getInventory().getItem(i); if (itemStack != null && itemStack.getType() != Material.AIR) { if (items.size() < 5) { if (itemStack.hasItemMeta()) { if (itemStack.getItemMeta().hasLore()) { ItemMeta meta = itemStack.getItemMeta(); meta.setLore(new ArrayList<String>()); itemStack.setItemMeta(meta); } if (itemStack.getItemMeta() instanceof BookMeta) { itemStack = removeBookContent(itemStack); } } items.add(itemStack); } else { items.add(new ItemStack(Material.STONE)); } } } inventoryHolder.getInventory().clear(); for (int i = 0; i < items.size(); i++) { inventoryHolder.getInventory().setItem(i, items.get(i)); } blockStateMeta.setBlockState((BlockState) inventoryHolder); item.setItemMeta(blockStateMeta); itemJson = ReflectionUtil.convertItemStackToJson(item); } else { itemJson = ReflectionUtil.convertItemStackToJson(item); } } catch (IllegalStateException e) { itemJson = ReflectionUtil.convertItemStackToJson(item); } } else { itemJson = ReflectionUtil.convertItemStackToJson(item); } HoverEvent ev = new HoverEvent(HoverEvent.Action.SHOW_ITEM, new BaseComponent[]{new TextComponent(itemJson)}); nameComponent.setHoverEvent(ev); if ("{itemName}".equals(display)) { result = nameComponent; } else { String[] plain = display.split("\\{itemName\\}"); result = new TextComponent(plain[0]); result.setHoverEvent(ev); for (int i = 1; i < plain.length; i++) { result.addExtra(nameComponent); TextComponent tmp = new TextComponent(plain[i].replace("{amount}", Integer.toString(item.getAmount()))); tmp.setHoverEvent(ev); result.addExtra(tmp); } } result.setHoverEvent(ev); inner.addExtra(result); return this; } public Message append(BaseComponent component) { inner.addExtra(component); return this; } public Message send(Player p) { p.spigot().sendMessage(inner); return this; } public Message broadcast() { Bukkit.getServer().spigot().broadcast(inner); return this; } public Message broadcast(String permission) { for (Player player : Bukkit.getOnlinePlayers()) { if (player.hasPermission(permission)) { this.send(player); } } return this; } public ItemStack removeBookContent(ItemStack item) { if (item.hasItemMeta() && item.getItemMeta() instanceof BookMeta) { ItemStack itemStack = item.clone(); BookMeta meta = (BookMeta) itemStack.getItemMeta(); meta.setPages(new ArrayList<String>()); itemStack.setItemMeta(meta); return itemStack; } return item; } }
broadcast message to console
src/main/java/cat/nyaa/utils/Message.java
broadcast message to console
Java
mit
2ef67ea28e05794dc522c3176edcedf3377fb4ff
0
bcgit/bc-java,bcgit/bc-java,bcgit/bc-java
package org.bouncycastle.asn1.ua; import org.bouncycastle.asn1.ASN1ObjectIdentifier; /** * Ukrainian object identifiers * <p> * {iso(1) member-body(2) Ukraine(804) root(2) security(1) cryptography(1) pki(1)} * <p> * { ... pki-alg(1) pki-alg-sym(3) Dstu4145WithGost34311(1) PB(1)} * <p> * DSTU4145 in polynomial basis has 2 oids, one for little-endian representation and one for big-endian */ public interface UAObjectIdentifiers { /** Base OID: 1.2.804.2.1.1.1 */ static final ASN1ObjectIdentifier UaOid = new ASN1ObjectIdentifier("1.2.804.2.1.1.1"); /** DSTU4145 Little Endian presentation. OID: 1.2.804.2.1.1.1.1.3.1.1 */ static final ASN1ObjectIdentifier dstu4145le = UaOid.branch("1.3.1.1"); /** DSTU4145 Big Endian presentation. OID: 1.2.804.2.1.1.1.1.3.1.1.1 */ static final ASN1ObjectIdentifier dstu4145be = UaOid.branch("1.3.1.1.1.1"); /** DSTU7564 256-bit digest presentation. */ static final ASN1ObjectIdentifier dstu7564digest_256 = UaOid.branch("1.2.2.1"); /** DSTU7564 384-bit digest presentation. */ static final ASN1ObjectIdentifier dstu7564digest_384 = UaOid.branch("1.2.2.2"); /** DSTU7564 512-bit digest presentation. */ static final ASN1ObjectIdentifier dstu7564digest_512 = UaOid.branch("1.2.2.3"); /** DSTU7564 256-bit mac presentation. */ static final ASN1ObjectIdentifier dstu7564mac_256 = UaOid.branch("1.2.2.4"); /** DSTU7564 384-bit mac presentation. */ static final ASN1ObjectIdentifier dstu7564mac_384 = UaOid.branch("1.2.2.5"); /** DSTU7564 512-bit mac presentation. */ static final ASN1ObjectIdentifier dstu7564mac_512 = UaOid.branch("1.2.2.6"); /** DSTU7624 in ECB mode with 128 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ecb_128 = UaOid.branch("1.1.3.1.1"); /** DSTU7624 in ECB mode with 256 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ecb_256 = UaOid.branch("1.1.3.1.2"); /** DSTU7624 in ECB mode with 512 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ecb_512 = UaOid.branch("1.1.3.1.3"); /** DSTU7624 in CTR mode with 128 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ctr_128 = UaOid.branch("1.1.3.2.1"); /** DSTU7624 in CTR mode with 256 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ctr_256 = UaOid.branch("1.1.3.2.2"); /** DSTU7624 in CTR mode with 512 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ctr_512 = UaOid.branch("1.1.3.2.3"); /** DSTU7624 in CFB mode with 128 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624cfb_128 = UaOid.branch("1.1.3.3.1"); /** DSTU7624 in CFB mode with 256 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624cfb_256 = UaOid.branch("1.1.3.3.2"); /** DSTU7624 in CFB mode with 512 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624cfb_512 = UaOid.branch("1.1.3.3.3"); /** DSTU7624 in MAC mode with 128 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624cmac_128 = UaOid.branch("1.1.3.4.1"); /** DSTU7624 in MAC mode with 256 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624cmac_256 = UaOid.branch("1.1.3.4.2"); /** DSTU7624 in MAC mode with 512 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624cmac_512 = UaOid.branch("1.1.3.4.3"); /** DSTU7624 in CBC mode with 128 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624cbc_128 = UaOid.branch("1.1.3.5.1"); /** DSTU7624 in CBC mode with 256 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624cbc_256 = UaOid.branch("1.1.3.5.2"); /** DSTU7624 in CBC mode with 512 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624cbc_512 = UaOid.branch("1.1.3.5.3"); /** DSTU7624 in OFB mode with 128 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ofb_128 = UaOid.branch("1.1.3.6.1"); /** DSTU7624 in OFB mode with 256 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ofb_256 = UaOid.branch("1.1.3.6.2"); /** DSTU7624 in OFB mode with 512 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ofb_512 = UaOid.branch("1.1.3.6.3"); /** DSTU7624 in GMAC (GCM witout encryption) mode with 128 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624gmac_128 = UaOid.branch("1.1.3.7.1"); /** DSTU7624 in GMAC (GCM witout encryption) mode with 256 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624gmac_256 = UaOid.branch("1.1.3.7.2"); /** DSTU7624 in GMAC (GCM witout encryption) mode with 512 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624gmac_512 = UaOid.branch("1.1.3.7.3"); /** DSTU7624 in CCM mode with 128 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ccm_128 = UaOid.branch("1.1.3.8.1"); /** DSTU7624 in CCM mode with 256 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ccm_256 = UaOid.branch("1.1.3.8.2"); /** DSTU7624 in CCM mode with 512 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624ccm_512 = UaOid.branch("1.1.3.8.3"); /** DSTU7624 in XTS mode with 128 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624xts_128 = UaOid.branch("1.1.3.9.1"); /** DSTU7624 in XTS mode with 256 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624xts_256 = UaOid.branch("1.1.3.9.2"); /** DSTU7624 in XTS mode with 512 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624xts_512 = UaOid.branch("1.1.3.9.3"); /** DSTU7624 in key wrap (KW) mode with 128 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624kw_128 = UaOid.branch("1.1.3.10.1"); /** DSTU7624 in key wrap (KW) mode with 256 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624kw_256 = UaOid.branch("1.1.3.10.2"); /** DSTU7624 in key wrap (KW) mode with 512 bit block/key presentation */ static final ASN1ObjectIdentifier dstu7624kw_512 = UaOid.branch("1.1.3.10.3"); }
core/src/main/java/org/bouncycastle/asn1/ua/UAObjectIdentifiers.java
package org.bouncycastle.asn1.ua; import org.bouncycastle.asn1.ASN1ObjectIdentifier; /** * Ukrainian object identifiers * <p> * {iso(1) member-body(2) Ukraine(804) root(2) security(1) cryptography(1) pki(1)} * <p> * { ... pki-alg(1) pki-alg-sym(3) Dstu4145WithGost34311(1) PB(1)} * <p> * DSTU4145 in polynomial basis has 2 oids, one for little-endian representation and one for big-endian */ public interface UAObjectIdentifiers { /** Base OID: 1.2.804.2.1.1.1 */ static final ASN1ObjectIdentifier UaOid = new ASN1ObjectIdentifier("1.2.804.2.1.1.1"); /** DSTU4145 Little Endian presentation. OID: 1.2.804.2.1.1.1.1.3.1.1 */ static final ASN1ObjectIdentifier dstu4145le = UaOid.branch("1.3.1.1"); /** DSTU4145 Big Endian presentation. OID: 1.2.804.2.1.1.1.1.3.1.1.1 */ static final ASN1ObjectIdentifier dstu4145be = UaOid.branch("1.3.1.1.1.1"); }
added DSTU7624, DSTU7654 OIDs.
core/src/main/java/org/bouncycastle/asn1/ua/UAObjectIdentifiers.java
added DSTU7624, DSTU7654 OIDs.
Java
mit
892fe144bb3051c4513afbbf7c11950f640b6de3
0
nallar/TickThreading
package me.nallar.patched.storage; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import com.google.common.collect.ImmutableSetMultimap; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.registry.GameRegistry; import me.nallar.patched.annotation.FakeExtend; import me.nallar.tickthreading.Log; import me.nallar.tickthreading.collections.NonBlockingLongSet; import me.nallar.tickthreading.minecraft.ChunkGarbageCollector; import me.nallar.tickthreading.minecraft.TickThreading; import me.nallar.tickthreading.patcher.Declare; import me.nallar.tickthreading.util.FakeServerThread; import me.nallar.tickthreading.util.concurrent.NativeMutex; import me.nallar.unsafe.UnsafeUtil; import net.minecraft.entity.EnumCreatureType; import net.minecraft.util.IProgressUpdate; import net.minecraft.util.LongHashMap; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.ChunkPosition; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.chunk.storage.IChunkLoader; import net.minecraft.world.gen.ChunkProviderServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.ChunkEvent; import org.cliffc.high_scale_lib.NonBlockingHashMapLong; /** * This is a replacement for ChunkProviderServer * Instead of attempting to patch a class with many different implementations, * this replaces it with an implementation which is intended to be compatible * with both Forge and MCPC+. */ @FakeExtend public abstract class ThreadedChunkProvider extends ChunkProviderServer implements IChunkProvider { /** * You may also use a synchronized block on generateLock, * and are encouraged to unless tryLock() is required. * This works as NativeMutex uses JVM monitors internally. */ public final NativeMutex generateLock = new NativeMutex(); private static final ThreadPoolExecutor chunkLoadThreadPool; static { int p = Runtime.getRuntime().availableProcessors(); chunkLoadThreadPool = new ThreadPoolExecutor(1, p, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(p * 10), new ServerThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy()); chunkLoadThreadPool.allowCoreThreadTimeOut(true); } private final NonBlockingHashMapLong<Object> chunkLoadLocks = new NonBlockingHashMapLong<Object>(); private final LongHashMap chunks = new LongHashMap(); private final LongHashMap loadingChunks = new LongHashMap(); private final LongHashMap unloadingChunks = new LongHashMap(); private final NonBlockingLongSet unloadStage0 = new NonBlockingLongSet(); private final ConcurrentLinkedQueue<QueuedUnload> unloadStage1 = new ConcurrentLinkedQueue<QueuedUnload>(); private final IChunkProvider generator; // Mojang shouldn't use the same interface for :( private final IChunkLoader loader; private final WorldServer world; private final ThreadLocal<Boolean> inUnload = new BooleanThreadLocal(); private int ticks = 0; private Chunk lastChunk; // Mojang compatiblity fields. public final Set<Long> chunksToUnload = unloadStage0; public final List<Chunk> loadedChunks; public final IChunkLoader currentChunkLoader; @SuppressWarnings ("UnusedDeclaration") public boolean loadChunkOnProvideRequest = true; public ThreadedChunkProvider(WorldServer world, IChunkLoader loader, IChunkProvider generator) { super(world, loader, generator); // This call will be removed by javassist. this.generator = generator; this.world = world; currentChunkLoader = this.loader = loader; loadedChunks = Collections.synchronizedList(new ArrayList<Chunk>()); } @Override @Declare public List<Chunk> getLoadedChunks() { return loadedChunks; } @Override @Declare public Set<Long> getChunksToUnloadSet() { return unloadStage0; } @Override public boolean unload100OldestChunks() { tick(); return generator.unload100OldestChunks(); } @SuppressWarnings ({"ConstantConditions", "FieldRepeatedlyAccessedInMethod"}) private void tick() { int ticks = this.ticks++; // Handle unload requests if (world.tickCount % 3 == 0 && !world.canNotSave && !unloadStage0.isEmpty()) { ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> persistentChunks = world.getPersistentChunks(); ChunkCoordIntPair chunkCoordIntPair = new ChunkCoordIntPair(0, 0); NonBlockingHashMapLong.IteratorLong i$ = unloadStage0.iteratorLong(); while (i$.hasNext()) { long key = i$.next(); i$.remove(); int x = (int) key; int z = (int) (key >> 32); chunkCoordIntPair.chunkXPos = x; chunkCoordIntPair.chunkZPos = z; if (persistentChunks.containsKey(chunkCoordIntPair) || unloadingChunks.containsItem(key)) { continue; } Chunk chunk = (Chunk) chunks.getValueByKey(key); if (chunk == null || chunk.unloading) { continue; } if (lastChunk == chunk) { lastChunk = null; } chunk.onChunkUnload(); loadedChunks.remove(chunk); chunks.remove(key); chunk.unloading = true; synchronized (unloadingChunks) { unloadingChunks.add(key, chunk); unloadStage1.add(new QueuedUnload(chunk, key, ticks)); } } if (loader != null) { loader.chunkTick(); } } long queueThreshold = ticks - 15; // Handle unloading stage 1 { QueuedUnload queuedUnload = unloadStage1.peek(); while (queuedUnload != null && queuedUnload.ticks <= queueThreshold) { Chunk chunk = queuedUnload.chunk; long chunkHash = queuedUnload.key; synchronized (unloadingChunks) { if (!unloadStage1.remove(queuedUnload) || unloadingChunks.remove(chunkHash) != chunk) { queuedUnload = unloadStage1.peek(); continue; } } finalizeUnload(chunk); queuedUnload = unloadStage1.peek(); } } if (ticks > 1200 && world.provider.dimensionId != 0 && TickThreading.instance.allowWorldUnloading && loadedChunks.isEmpty() && ForgeChunkManager.getPersistentChunksFor(world).isEmpty() && (!TickThreading.instance.shouldLoadSpawn || !DimensionManager.shouldLoadSpawn(world.provider.dimensionId))) { DimensionManager.unloadWorld(world.provider.dimensionId); } if (ticks % TickThreading.instance.chunkGCInterval == 0) { ChunkGarbageCollector.garbageCollect(world); } } private void finalizeUnload(Chunk chunk) { if (!chunk.unloading) { throw new IllegalArgumentException("Chunk " + chunk + " is not unloading."); } if (chunk.alreadySavedAfterUnload) { return; } boolean notInUnload = !inUnload.get(); if (notInUnload) { inUnload.set(true); } chunk.alreadySavedAfterUnload = true; chunk.isChunkLoaded = false; MinecraftForge.EVENT_BUS.post(new ChunkEvent.Unload(chunk)); safeSaveChunk(chunk); safeSaveExtraChunkData(chunk); if (notInUnload) { inUnload.set(false); } } // Public visibility as it will be accessed from net.minecraft.whatever, not actually this class // (Inner classes are not remapped in patching) public static class QueuedUnload implements Comparable<QueuedUnload> { public final int ticks; public final long key; public final Chunk chunk; public QueuedUnload(Chunk chunk, long key, int ticks) { this.chunk = chunk; this.key = key; this.ticks = ticks; } @Override public int compareTo(QueuedUnload o) { long t1 = o.ticks; long t2 = ticks; return t1 == t2 ? 0 : (t1 < t2 ? -1 : 1); } } @Override public boolean chunkExists(int x, int z) { return chunks.containsItem(key(x, z)); } @Override @Declare public boolean unloadChunk(int x, int z) { long hash = key(x, z); return chunks.containsItem(hash) && unloadStage0.add(hash); } @Override public void unloadChunksIfNotNearSpawn(int x, int z) { unloadChunk(x, z); } @Override public void unloadAllChunks() { synchronized (loadedChunks) { for (Chunk chunk : loadedChunks) { unloadStage0.add(key(chunk.xPosition, chunk.zPosition)); } } } public Object getLock(int x, int z) { long hash = key(x, z); Object lock = chunkLoadLocks.get(hash); if (lock != null) { return lock; } Object newLock = new Object(); lock = chunkLoadLocks.putIfAbsent(hash, newLock); if (lock != null) { return lock; } return newLock; } @Override public Chunk provideChunk(int x, int z) { return getChunkAt(x, z, null); } @Override public Chunk loadChunk(int x, int z) { return getChunkAt(x, z, null); } @Override @SuppressWarnings ("ConstantConditions") @Declare public Chunk getChunkAt(final int x, final int z, final Runnable runnable) { Chunk chunk = getChunkIfExists(x, z); if (chunk != null) { if (runnable != null) { runnable.run(); } return chunk; } if (runnable != null) { chunkLoadThreadPool.execute(new ChunkLoadRunnable(x, z, runnable, this)); return null; } long key = key(x, z); final Object lock = getLock(x, z); boolean inLoadingMap = false; // Lock on the lock for this chunk - prevent multiple instances of the same chunk ThreadLocal<Boolean> worldGenInProgress = world.worldGenInProgress; synchronized (lock) { synchronized (unloadingChunks) { chunk = (Chunk) unloadingChunks.remove(key); } if (chunk != null && !inUnload.get()) { finalizeUnload(chunk); } chunk = (Chunk) chunks.getValueByKey(key); if (chunk != null) { return chunk; } chunk = (Chunk) loadingChunks.getValueByKey(key); if (chunk == null) { chunk = safeLoadChunk(x, z); if (chunk != null) { loadingChunks.add(key, chunk); inLoadingMap = true; } } else if (worldGenInProgress != null && worldGenInProgress.get() == Boolean.TRUE) { return chunk; } else { inLoadingMap = true; } } // Unlock this chunk - avoids a deadlock // Thread A - requests chunk A - needs genned // Thread B - requests chunk B - needs genned // In thread A, redpower tries to load chunk B // because its marble gen is buggy. // Thread B is now waiting for the generate lock, // Thread A is waiting for the lock on chunk B // Lock the generation lock - ChunkProviderGenerate isn't threadsafe at all // TODO: Possibly make ChunkProviderGenerate threadlocal? Would need many changes to // structure code to get it to work properly. boolean innerGenerate = false; try { synchronized (generateLock) { synchronized (lock) { if (worldGenInProgress != null) { if (!(innerGenerate = (worldGenInProgress.get() == Boolean.TRUE))) { worldGenInProgress.set(Boolean.TRUE); } } chunk = (Chunk) chunks.getValueByKey(key); if (chunk != null) { return chunk; } chunk = (Chunk) loadingChunks.getValueByKey(key); if (chunk == null) { if (generator == null) { chunk = defaultEmptyChunk; } else { try { chunk = generator.provideChunk(x, z); } catch (Throwable t) { Log.severe("Failed to generate a chunk in " + Log.name(world) + " at chunk coords " + x + ',' + z); throw UnsafeUtil.throwIgnoreChecked(t); } } } else { if (generator != null) { generator.recreateStructures(x, z); } } if (chunk == null) { throw new IllegalStateException("Null chunk was provided for " + x + ',' + z); } if (!inLoadingMap) { loadingChunks.add(key, chunk); } chunk.populateChunk(this, this, x, z); chunk.threadUnsafeChunkLoad(); loadingChunks.remove(key); chunks.add(key, chunk); loadedChunks.add(chunk); } } } finally { if (!innerGenerate && worldGenInProgress != null) { worldGenInProgress.set(Boolean.FALSE); } } // TODO: Do initial mob spawning here - doing it while locked is stupid and can cause deadlocks with some bukkit plugins chunk.onChunkLoad(); chunkLoadLocks.remove(key); return chunk; } @Override protected Chunk safeLoadChunk(int x, int z) { if (loader == null) { return null; } try { Chunk chunk = loader.loadChunk(world, x, z); if (chunk != null) { chunk.lastSaveTime = world.getTotalWorldTime(); } return chunk; } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Failed to load chunk at " + x + ',' + z); return null; } } @Override protected void safeSaveExtraChunkData(Chunk chunk) { if (loader == null) { return; } try { loader.saveExtraChunkData(world, chunk); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Failed to save extra chunk data for " + chunk); } } @Override protected void safeSaveChunk(Chunk chunk) { if (loader == null) { return; } try { chunk.lastSaveTime = world.getTotalWorldTime(); loader.saveChunk(world, chunk); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Failed to save chunk " + chunk); } } @Override public void populate(IChunkProvider chunkProvider, int x, int z) { synchronized (generateLock) { Chunk var4 = provideChunk(x, z); if (!var4.isTerrainPopulated) { var4.isTerrainPopulated = true; if (generator != null) { generator.populate(chunkProvider, x, z); GameRegistry.generateWorld(x, z, world, generator, chunkProvider); var4.setChunkModified(); } } } } @Override public boolean saveChunks(boolean saveAll, IProgressUpdate progressUpdate) { int savedChunks = 0; synchronized (loadedChunks) { for (Chunk chunk : loadedChunks) { if (chunk.unloading) { if (saveAll) { chunk.alreadySavedAfterUnload = true; } else { continue; } } if (saveAll) { safeSaveExtraChunkData(chunk); } if (chunk.needsSaving(saveAll)) { safeSaveChunk(chunk); chunk.isModified = false; if (++savedChunks == 24 && !saveAll) { return false; } } } } if (saveAll && loader != null) { loader.saveExtraData(); } return true; } @Override public boolean canSave() { return !world.canNotSave; } @Override public String makeString() { return "Loaded " + loadedChunks.size() + " Unload0 " + unloadStage0.size() + " Unload1 " + unloadStage1.size(); } @Override public List getPossibleCreatures(EnumCreatureType creatureType, int x, int y, int z) { return generator.getPossibleCreatures(creatureType, x, y, z); } @Override public ChunkPosition findClosestStructure(World world, String name, int x, int y, int z) { return generator.findClosestStructure(world, name, x, y, z); } @Override public int getLoadedChunkCount() { return loadedChunks.size(); } @Override public void recreateStructures(int x, int z) { } @Override @Declare public Chunk getChunkIfExists(int x, int z) { Chunk chunk = lastChunk; if (chunk != null && chunk.xPosition == x && chunk.zPosition == z) { return chunk; } chunk = (Chunk) chunks.getValueByKey(key(x, z)); if (chunk == null) { return null; } lastChunk = chunk; return chunk; } private static long key(int x, int z) { return (((long) z) << 32) | (x & 0xffffffffL); } public static class ChunkLoadRunnable implements Runnable { private final int x; private final int z; private final Runnable runnable; private final ChunkProviderServer provider; public ChunkLoadRunnable(int x, int z, Runnable runnable, ChunkProviderServer provider) { this.x = x; this.z = z; this.runnable = runnable; this.provider = provider; } @Override public void run() { try { Chunk ch = provider.getChunkAt(x, z, null); if (ch == null) { FMLLog.warning("Failed to load chunk at " + x + ',' + z + " asynchronously."); } else { runnable.run(); } } catch (Throwable t) { FMLLog.log(Level.SEVERE, t, "Exception loading chunk asynchronously."); } } } public static class ServerThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { return new FakeServerThread(r, "Async ChunkLoader", true); } } public static class BooleanThreadLocal extends ThreadLocal<Boolean> { @Override public Boolean initialValue() { return false; } } }
src/common/me/nallar/patched/storage/ThreadedChunkProvider.java
package me.nallar.patched.storage; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import com.google.common.collect.ImmutableSetMultimap; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.registry.GameRegistry; import me.nallar.patched.annotation.FakeExtend; import me.nallar.tickthreading.Log; import me.nallar.tickthreading.collections.NonBlockingLongSet; import me.nallar.tickthreading.minecraft.ChunkGarbageCollector; import me.nallar.tickthreading.minecraft.TickThreading; import me.nallar.tickthreading.patcher.Declare; import me.nallar.tickthreading.util.FakeServerThread; import me.nallar.tickthreading.util.concurrent.NativeMutex; import me.nallar.unsafe.UnsafeUtil; import net.minecraft.entity.EnumCreatureType; import net.minecraft.util.IProgressUpdate; import net.minecraft.util.LongHashMap; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.ChunkPosition; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.chunk.storage.IChunkLoader; import net.minecraft.world.gen.ChunkProviderServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.ChunkEvent; import org.cliffc.high_scale_lib.NonBlockingHashMapLong; /** * This is a replacement for ChunkProviderServer * Instead of attempting to patch a class with many different implementations, * this replaces it with an implementation which is intended to be compatible * with both Forge and MCPC+. */ @FakeExtend public abstract class ThreadedChunkProvider extends ChunkProviderServer implements IChunkProvider { /** * You may also use a synchronized block on generateLock, * and are encouraged to unless tryLock() is required. * This works as NativeMutex uses JVM monitors internally. */ public final NativeMutex generateLock = new NativeMutex(); private static final ThreadPoolExecutor chunkLoadThreadPool; static { int p = Runtime.getRuntime().availableProcessors(); chunkLoadThreadPool = new ThreadPoolExecutor(1, p, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(p * 10), new ServerThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy()); chunkLoadThreadPool.allowCoreThreadTimeOut(true); } private final NonBlockingHashMapLong<Object> chunkLoadLocks = new NonBlockingHashMapLong<Object>(); private final LongHashMap chunks = new LongHashMap(); private final LongHashMap loadingChunks = new LongHashMap(); private final LongHashMap unloadingChunks = new LongHashMap(); private final NonBlockingLongSet unloadStage0 = new NonBlockingLongSet(); private final ConcurrentLinkedQueue<QueuedUnload> unloadStage1 = new ConcurrentLinkedQueue<QueuedUnload>(); private final IChunkProvider generator; // Mojang shouldn't use the same interface for :( private final IChunkLoader loader; private final WorldServer world; private final ThreadLocal<Boolean> inUnload = new BooleanThreadLocal(); private int ticks = 0; private Chunk lastChunk; // Mojang compatiblity fields. public final Set<Long> chunksToUnload = unloadStage0; public final List<Chunk> loadedChunks; public final IChunkLoader currentChunkLoader; @SuppressWarnings ("UnusedDeclaration") public boolean loadChunkOnProvideRequest = true; public ThreadedChunkProvider(WorldServer world, IChunkLoader loader, IChunkProvider generator) { super(world, loader, generator); // This call will be removed by javassist. this.generator = generator; this.world = world; currentChunkLoader = this.loader = loader; loadedChunks = Collections.synchronizedList(new ArrayList<Chunk>()); } @Override @Declare public List<Chunk> getLoadedChunks() { return loadedChunks; } @Override @Declare public Set<Long> getChunksToUnloadSet() { return unloadStage0; } @Override public boolean unload100OldestChunks() { tick(); return generator.unload100OldestChunks(); } @SuppressWarnings ({"ConstantConditions", "FieldRepeatedlyAccessedInMethod"}) private void tick() { int ticks = this.ticks++; // Handle unload requests if (world.tickCount % 3 == 0 && !world.canNotSave && !unloadStage0.isEmpty()) { ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> persistentChunks = world.getPersistentChunks(); ChunkCoordIntPair chunkCoordIntPair = new ChunkCoordIntPair(0, 0); NonBlockingHashMapLong.IteratorLong i$ = unloadStage0.iteratorLong(); while (i$.hasNext()) { long key = i$.next(); i$.remove(); int x = (int) key; int z = (int) (key >> 32); chunkCoordIntPair.chunkXPos = x; chunkCoordIntPair.chunkZPos = z; if (persistentChunks.containsKey(chunkCoordIntPair) || unloadingChunks.containsItem(key)) { continue; } Chunk chunk = (Chunk) chunks.getValueByKey(key); if (chunk == null || chunk.unloading) { continue; } if (lastChunk == chunk) { lastChunk = null; } chunk.onChunkUnload(); loadedChunks.remove(chunk); chunks.remove(key); chunk.unloading = true; synchronized (unloadingChunks) { unloadingChunks.add(key, chunk); unloadStage1.add(new QueuedUnload(chunk, key, ticks)); } } if (loader != null) { loader.chunkTick(); } } long queueThreshold = ticks - 15; // Handle unloading stage 1 { QueuedUnload queuedUnload = unloadStage1.peek(); while (queuedUnload != null && queuedUnload.ticks <= queueThreshold) { Chunk chunk = queuedUnload.chunk; long chunkHash = queuedUnload.key; synchronized (unloadingChunks) { if (!unloadStage1.remove(queuedUnload) || unloadingChunks.remove(chunkHash) != chunk) { queuedUnload = unloadStage1.peek(); continue; } } finalizeUnload(chunk); queuedUnload = unloadStage1.peek(); } } if (ticks > 1200 && world.provider.dimensionId != 0 && TickThreading.instance.allowWorldUnloading && loadedChunks.isEmpty() && ForgeChunkManager.getPersistentChunksFor(world).isEmpty() && (!TickThreading.instance.shouldLoadSpawn || !DimensionManager.shouldLoadSpawn(world.provider.dimensionId))) { DimensionManager.unloadWorld(world.provider.dimensionId); } if (ticks % TickThreading.instance.chunkGCInterval == 0) { ChunkGarbageCollector.garbageCollect(world); } } private void finalizeUnload(Chunk chunk) { if (!chunk.unloading) { throw new IllegalArgumentException("Chunk " + chunk + " is not unloading."); } if (chunk.alreadySavedAfterUnload) { return; } boolean notInUnload = !inUnload.get(); if (notInUnload) { inUnload.set(true); } chunk.alreadySavedAfterUnload = true; chunk.isChunkLoaded = false; MinecraftForge.EVENT_BUS.post(new ChunkEvent.Unload(chunk)); safeSaveChunk(chunk); safeSaveExtraChunkData(chunk); if (notInUnload) { inUnload.set(false); } } // Public visibility as it will be accessed from net.minecraft.whatever, not actually this class // (Inner classes are not remapped in patching) public static class QueuedUnload implements Comparable<QueuedUnload> { public final int ticks; public final long key; public final Chunk chunk; public QueuedUnload(Chunk chunk, long key, int ticks) { this.chunk = chunk; this.key = key; this.ticks = ticks; } @Override public int compareTo(QueuedUnload o) { long t1 = o.ticks; long t2 = ticks; return t1 == t2 ? 0 : (t1 < t2 ? -1 : 1); } } @Override public boolean chunkExists(int x, int z) { return chunks.containsItem(key(x, z)); } @Override public void unloadChunksIfNotNearSpawn(int x, int z) { unloadStage0.add(key(x, z)); } @Override public void unloadAllChunks() { synchronized (loadedChunks) { for (Chunk chunk : loadedChunks) { unloadStage0.add(key(chunk.xPosition, chunk.zPosition)); } } } public Object getLock(int x, int z) { long hash = key(x, z); Object lock = chunkLoadLocks.get(hash); if (lock != null) { return lock; } Object newLock = new Object(); lock = chunkLoadLocks.putIfAbsent(hash, newLock); if (lock != null) { return lock; } return newLock; } @Override public Chunk provideChunk(int x, int z) { return getChunkAt(x, z, null); } @Override public Chunk loadChunk(int x, int z) { return getChunkAt(x, z, null); } @Override @SuppressWarnings ("ConstantConditions") @Declare public Chunk getChunkAt(final int x, final int z, final Runnable runnable) { Chunk chunk = getChunkIfExists(x, z); if (chunk != null) { if (runnable != null) { runnable.run(); } return chunk; } if (runnable != null) { chunkLoadThreadPool.execute(new ChunkLoadRunnable(x, z, runnable, this)); return null; } long key = key(x, z); final Object lock = getLock(x, z); boolean inLoadingMap = false; // Lock on the lock for this chunk - prevent multiple instances of the same chunk ThreadLocal<Boolean> worldGenInProgress = world.worldGenInProgress; synchronized (lock) { synchronized (unloadingChunks) { chunk = (Chunk) unloadingChunks.remove(key); } if (chunk != null && !inUnload.get()) { finalizeUnload(chunk); } chunk = (Chunk) chunks.getValueByKey(key); if (chunk != null) { return chunk; } chunk = (Chunk) loadingChunks.getValueByKey(key); if (chunk == null) { chunk = safeLoadChunk(x, z); if (chunk != null) { loadingChunks.add(key, chunk); inLoadingMap = true; } } else if (worldGenInProgress != null && worldGenInProgress.get() == Boolean.TRUE) { return chunk; } else { inLoadingMap = true; } } // Unlock this chunk - avoids a deadlock // Thread A - requests chunk A - needs genned // Thread B - requests chunk B - needs genned // In thread A, redpower tries to load chunk B // because its marble gen is buggy. // Thread B is now waiting for the generate lock, // Thread A is waiting for the lock on chunk B // Lock the generation lock - ChunkProviderGenerate isn't threadsafe at all // TODO: Possibly make ChunkProviderGenerate threadlocal? Would need many changes to // structure code to get it to work properly. boolean innerGenerate = false; try { synchronized (generateLock) { synchronized (lock) { if (worldGenInProgress != null) { if (!(innerGenerate = (worldGenInProgress.get() == Boolean.TRUE))) { worldGenInProgress.set(Boolean.TRUE); } } chunk = (Chunk) chunks.getValueByKey(key); if (chunk != null) { return chunk; } chunk = (Chunk) loadingChunks.getValueByKey(key); if (chunk == null) { if (generator == null) { chunk = defaultEmptyChunk; } else { try { chunk = generator.provideChunk(x, z); } catch (Throwable t) { Log.severe("Failed to generate a chunk in " + Log.name(world) + " at chunk coords " + x + ',' + z); throw UnsafeUtil.throwIgnoreChecked(t); } } } else { if (generator != null) { generator.recreateStructures(x, z); } } if (chunk == null) { throw new IllegalStateException("Null chunk was provided for " + x + ',' + z); } if (!inLoadingMap) { loadingChunks.add(key, chunk); } chunk.populateChunk(this, this, x, z); chunk.threadUnsafeChunkLoad(); loadingChunks.remove(key); chunks.add(key, chunk); loadedChunks.add(chunk); } } } finally { if (!innerGenerate && worldGenInProgress != null) { worldGenInProgress.set(Boolean.FALSE); } } // TODO: Do initial mob spawning here - doing it while locked is stupid and can cause deadlocks with some bukkit plugins chunk.onChunkLoad(); chunkLoadLocks.remove(key); return chunk; } @Override protected Chunk safeLoadChunk(int x, int z) { if (loader == null) { return null; } try { Chunk chunk = loader.loadChunk(world, x, z); if (chunk != null) { chunk.lastSaveTime = world.getTotalWorldTime(); } return chunk; } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Failed to load chunk at " + x + ',' + z); return null; } } @Override protected void safeSaveExtraChunkData(Chunk chunk) { if (loader == null) { return; } try { loader.saveExtraChunkData(world, chunk); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Failed to save extra chunk data for " + chunk); } } @Override protected void safeSaveChunk(Chunk chunk) { if (loader == null) { return; } try { chunk.lastSaveTime = world.getTotalWorldTime(); loader.saveChunk(world, chunk); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Failed to save chunk " + chunk); } } @Override public void populate(IChunkProvider chunkProvider, int x, int z) { synchronized (generateLock) { Chunk var4 = provideChunk(x, z); if (!var4.isTerrainPopulated) { var4.isTerrainPopulated = true; if (generator != null) { generator.populate(chunkProvider, x, z); GameRegistry.generateWorld(x, z, world, generator, chunkProvider); var4.setChunkModified(); } } } } @Override public boolean saveChunks(boolean saveAll, IProgressUpdate progressUpdate) { int savedChunks = 0; synchronized (loadedChunks) { for (Chunk chunk : loadedChunks) { if (chunk.unloading) { if (saveAll) { chunk.alreadySavedAfterUnload = true; } else { continue; } } if (saveAll) { safeSaveExtraChunkData(chunk); } if (chunk.needsSaving(saveAll)) { safeSaveChunk(chunk); chunk.isModified = false; if (++savedChunks == 24 && !saveAll) { return false; } } } } if (saveAll && loader != null) { loader.saveExtraData(); } return true; } @Override public boolean canSave() { return !world.canNotSave; } @Override public String makeString() { return "Loaded " + loadedChunks.size() + " Unload0 " + unloadStage0.size() + " Unload1 " + unloadStage1.size(); } @Override public List getPossibleCreatures(EnumCreatureType creatureType, int x, int y, int z) { return generator.getPossibleCreatures(creatureType, x, y, z); } @Override public ChunkPosition findClosestStructure(World world, String name, int x, int y, int z) { return generator.findClosestStructure(world, name, x, y, z); } @Override public int getLoadedChunkCount() { return loadedChunks.size(); } @Override public void recreateStructures(int x, int z) { } @Override @Declare public Chunk getChunkIfExists(int x, int z) { Chunk chunk = lastChunk; if (chunk != null && chunk.xPosition == x && chunk.zPosition == z) { return chunk; } chunk = (Chunk) chunks.getValueByKey(key(x, z)); if (chunk == null) { return null; } lastChunk = chunk; return chunk; } private static long key(int x, int z) { return (((long) z) << 32) | (x & 0xffffffffL); } public static class ChunkLoadRunnable implements Runnable { private final int x; private final int z; private final Runnable runnable; private final ChunkProviderServer provider; public ChunkLoadRunnable(int x, int z, Runnable runnable, ChunkProviderServer provider) { this.x = x; this.z = z; this.runnable = runnable; this.provider = provider; } @Override public void run() { try { Chunk ch = provider.getChunkAt(x, z, null); if (ch == null) { FMLLog.warning("Failed to load chunk at " + x + ',' + z + " asynchronously."); } else { runnable.run(); } } catch (Throwable t) { FMLLog.log(Level.SEVERE, t, "Exception loading chunk asynchronously."); } } } public static class ServerThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { return new FakeServerThread(r, "Async ChunkLoader", true); } } public static class BooleanThreadLocal extends ThreadLocal<Boolean> { @Override public Boolean initialValue() { return false; } } }
Only add to unload queue if loaded. Signed-off-by: Ross Allan <ca2c77e14df1e7ee673215c1ef658354e220f471@gmail.com>
src/common/me/nallar/patched/storage/ThreadedChunkProvider.java
Only add to unload queue if loaded.
Java
mit
12ff69a44d5628208d0249137337934322b9faae
0
rweekers/voornameninliedjes-backend-spring
package org.orangeflamingo.voornaaminliedje.springconfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin") .password("5095df0e6547e2647d5bc40f1ecd9afe").roles("ADMIN"); auth.inMemoryAuthentication().withUser("Remco").password("ccafbc2f4c5e0d2b262ff070476678b7") .roles("ADMIN"); auth.inMemoryAuthentication().withUser("Nadja").password("82adbb3e824d6e62038273b8e6ac3eb4") .roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/api/admin/**").permitAll() .antMatchers(HttpMethod.POST, "/api/song/**").permitAll() .antMatchers(HttpMethod.GET, "/api/song/**").permitAll() .antMatchers(HttpMethod.POST, "/api/visit/**").permitAll() .antMatchers(HttpMethod.GET, "/api/visit/**").permitAll() .antMatchers(HttpMethod.GET, "/api/admin/**").hasRole("ADMIN") .and().httpBasic().and().csrf().disable(); } }
voornaaminliedje-backend/src/main/java/org/orangeflamingo/voornaaminliedje/springconfig/SecurityConfig.java
package org.orangeflamingo.voornaaminliedje.springconfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin") .password("5095df0e6547e2647d5bc40f1ecd9afe").roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/api/admin/**").permitAll() .antMatchers(HttpMethod.POST, "/api/song/**").permitAll() .antMatchers(HttpMethod.GET, "/api/song/**").permitAll() .antMatchers(HttpMethod.POST, "/api/visit/**").permitAll() .antMatchers(HttpMethod.GET, "/api/visit/**").permitAll() .antMatchers(HttpMethod.GET, "/api/admin/**").hasRole("ADMIN") .and().httpBasic().and().csrf().disable(); } }
Updated security with users Remco and Nadja.
voornaaminliedje-backend/src/main/java/org/orangeflamingo/voornaaminliedje/springconfig/SecurityConfig.java
Updated security with users Remco and Nadja.
Java
cc0-1.0
aae69ed36082249d6172109e00cf19d493045ea1
0
degaulledai/Set-Game
/** * Represents a generic deck of cards. */ /* Tips: - Use an cardArray<Card> to hold the cards. - Add and remove cards at the end of the list. - Use Collections.shuffle and Collections.sort to shuffle and sort the deck, or write your own methods. If you write your own, use selection sort to sort and a similar algorithm to shuffle. Use Math.random(). - In the toString method, separate strings for individual cards with "\n". */ import java.util.*; public class Deck { private ArrayList <Card> cardArray; public Deck () { cardArray = new ArrayList <Card> (); } public void add (Card card) { cardArray.add(card); } public void remove (Card card) { cardArray.remove(card); } public int getNumCards() { return cardArray.size(); } public boolean isEmpty() { return cardArray.isEmpty(); } public void shuffle () { Collections.shuffle (cardArray); } public void sort () { Collections.sort (cardArray); } public Card takeTop() { return cardArray.get(0); } public String toString () { String str=""; for (int i=0; i<cardArray.size(); i++) { str+= cardArray.get(i) + "\n"; } return str; } }
CodeHandouts/Group1/Deck.java
/** * Represents a generic deck of cards. */ /* Tips: - Use an cardArray<Card> to hold the cards. - Add and remove cards at the end of the list. - Use Collections.shuffle and Collections.sort to shuffle and sort the deck, or write your own methods. If you write your own, use selection sort to sort and a similar algorithm to shuffle. Use Math.random(). - In the toString method, separate strings for individual cards with "\n". */ import java.util.*; public class Deck { private ArrayList <Card> cardArray; public Deck (int capacity) { cardArray = new ArrayList <Card> (capacity); } public void add (Card card) { cardArray.add(card); } public void remove (Card card) { cardArray.remove(card); } public int getNumCards() { return cardArray.size(); } public boolean isEmpty() { return cardArray.isEmpty(); } public void shuffle () { Collections.shuffle (cardArray); } public void sort () { Collections.sort (cardArray); } public Card takeTop() { return cardArray.get(0); } public String toString () { String str=""; for (int i=0; i<cardArray.size(); i++) { str+= cardArray.get(i) + "\n"; } return str; } }
Update Deck.java
CodeHandouts/Group1/Deck.java
Update Deck.java
Java
epl-1.0
513c729e710ec20a05810f166a784b2156ed3335
0
spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4
/******************************************************************************* * Copyright (c) 2018 Pivotal, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Pivotal, Inc. - initial API and implementation *******************************************************************************/ package org.springframework.ide.vscode.commons.boot.app.cli; import java.util.Set; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ide.vscode.commons.util.StringUtil; public class ContextPath { protected static Logger logger = LoggerFactory.getLogger(ContextPath.class); public static final String[] CONTEXTPATH = { "server.context-path", "server.contextPath", "SERVER_CONTEXT_PATH", "server.servlet.context-path", "server.servlet.contextPath", "SERVER_SERVLET_CONTEXT_PATH" }; public static String getContextPath(String environment) { if (environment != null) { JSONObject env = new JSONObject(environment); for (String prop : CONTEXTPATH) { String contextPath = findContextPath(env, prop); if (StringUtil.hasText(contextPath)) { return contextPath; } } } return null; } private static String findContextPath(JSONObject env, String contextPathProp) { String contextPath = null; if (env != null) { // Properties defined in command line args have higher priority over // those defined in application configuration files (properties/yaml files) contextPath = findInCommandLineArgs(env, contextPathProp); if (contextPath == null) { contextPath = findInApplicationConfig(env, contextPathProp); } } return contextPath; } private static String findInApplicationConfig(JSONObject env, String contextPathProp) { // boot 1.x JSONObject applicationConfig = null; for (String key : env.keySet()) { if (key.startsWith("applicationConfig")) { applicationConfig = env.getJSONObject(key); if (applicationConfig != null) { String contextPathValue = applicationConfig.optString(contextPathProp); // Warning: fetching value above may return empty string, so null check on the // value is not enough if (StringUtil.hasText(contextPathValue)) { return contextPathValue; } } } } // boot 2.x if (applicationConfig == null) { // Not found as direct property value... in Boot 2.0 we must look inside the // 'propertySources'. // Similar... but structure is more complex. JSONArray propertySources = env.optJSONArray("propertySources"); if (propertySources != null) { for (Object _source : propertySources) { if (_source instanceof JSONObject) { JSONObject source = (JSONObject) _source; String sourceName = source.optString("name"); if (sourceName != null && sourceName.startsWith("applicationConfig")) { JSONObject props = source.optJSONObject("properties"); Set<String> keySet = props.keySet(); // Check that the context is a key before retrieving the JSON object value. // Note: attempting to fetch the JSON object value on a key that may not exist // throws exception // thus the reason why we are checking that the key exists first if (keySet.contains(contextPathProp)) { JSONObject jsonObject = props.getJSONObject(contextPathProp); if (jsonObject != null) { String contextPathValue = jsonObject.optString("value"); if (StringUtil.hasText(contextPathValue)) { return contextPathValue; } } } } } } } } return null; } protected static String findInCommandLineArgs(JSONObject env, String contextPathProp) { // boot 1.x JSONObject commandLineArgs = env.optJSONObject("commandLineArgs"); if (commandLineArgs != null) { String contextPathValue = commandLineArgs.optString(contextPathProp); // Warning: fetching value above may return empty string, so null check on the // value is not enough if (StringUtil.hasText(contextPathValue)) { return contextPathValue; } } // boot 2.x if (commandLineArgs == null) { // Not found as direct property value... in Boot 2.0 we must look inside the // 'propertySources'. // Similar... but structure is more complex. JSONArray propertySources = env.optJSONArray("propertySources"); if (propertySources != null) { for (Object _source : propertySources) { if (_source instanceof JSONObject) { JSONObject source = (JSONObject) _source; String sourceName = source.optString("name"); if ("commandLineArgs".equals(sourceName)) { JSONObject props = source.optJSONObject("properties"); // Find the contextPathProp in the command line args JSONObject valueObject = props.optJSONObject(contextPathProp); if (valueObject != null) { String contextPathValue = valueObject.optString("value"); if (StringUtil.hasText(contextPathValue)) { return contextPathValue; } } } } } } } return null; } }
headless-services/commons/commons-boot-app-cli/src/main/java/org/springframework/ide/vscode/commons/boot/app/cli/ContextPath.java
/******************************************************************************* * Copyright (c) 2018 Pivotal, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Pivotal, Inc. - initial API and implementation *******************************************************************************/ package org.springframework.ide.vscode.commons.boot.app.cli; import java.util.Set; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ide.vscode.commons.util.StringUtil; public class ContextPath { protected static Logger logger = LoggerFactory.getLogger(ContextPath.class); public static final String[] CONTEXTPATH = { "server.context-path", "server.contextPath", "SERVER_CONTEXT_PATH", "server.servlet.context-path", "server.servlet.contextPath", "SERVER_SERVLET_CONTEXT_PATH" }; public static String getContextPath(String environment) { if (environment != null) { JSONObject env = new JSONObject(environment); for (String prop : CONTEXTPATH) { String contextPath = findContextPath(env, prop); if (StringUtil.hasText(contextPath)) { return contextPath; } } } return null; } private static String findContextPath(JSONObject env, String contextPathProp) { String contextPath = null; if (env != null) { contextPath = findInCommandLineArgs(env, contextPathProp); if (contextPath == null) { contextPath = findInApplicationConfig(env, contextPathProp); } } return contextPath; } private static String findInApplicationConfig(JSONObject env, String contextPathProp) { // boot 1.x JSONObject applicationConfig = null; for (String key : env.keySet()) { if (key.startsWith("applicationConfig")) { applicationConfig = env.getJSONObject(key); if (applicationConfig != null) { String contextPathValue = applicationConfig.optString(contextPathProp); // Warning: fetching value above may return empty string, so null check on the // value is not enough if (StringUtil.hasText(contextPathValue)) { return contextPathValue; } } } } // boot 2.x if (applicationConfig == null) { // Not found as direct property value... in Boot 2.0 we must look inside the // 'propertySources'. // Similar... but structure is more complex. JSONArray propertySources = env.optJSONArray("propertySources"); if (propertySources != null) { for (Object _source : propertySources) { if (_source instanceof JSONObject) { JSONObject source = (JSONObject) _source; String sourceName = source.optString("name"); if (sourceName != null && sourceName.startsWith("applicationConfig")) { JSONObject props = source.optJSONObject("properties"); Set<String> keySet = props.keySet(); // Check that the context is a key before retrieving the JSON object value. // Note: attempting to fetch the JSON object value on a key that may not exist // throws exception // thus the reason why we are checking that the key exists first if (keySet.contains(contextPathProp)) { JSONObject jsonObject = props.getJSONObject(contextPathProp); if (jsonObject != null) { String contextPathValue = jsonObject.optString("value"); if (StringUtil.hasText(contextPathValue)) { return contextPathValue; } } } } } } } } return null; } protected static String findInCommandLineArgs(JSONObject env, String contextPathProp) { // boot 1.x JSONObject commandLineArgs = env.optJSONObject("commandLineArgs"); if (commandLineArgs != null) { String contextPathValue = commandLineArgs.optString(contextPathProp); // Warning: fetching value above may return empty string, so null check on the // value is not enough if (StringUtil.hasText(contextPathValue)) { return contextPathValue; } } // boot 2.x if (commandLineArgs == null) { // Not found as direct property value... in Boot 2.0 we must look inside the // 'propertySources'. // Similar... but structure is more complex. JSONArray propertySources = env.optJSONArray("propertySources"); if (propertySources != null) { for (Object _source : propertySources) { if (_source instanceof JSONObject) { JSONObject source = (JSONObject) _source; String sourceName = source.optString("name"); if ("commandLineArgs".equals(sourceName)) { JSONObject props = source.optJSONObject("properties"); // Find the contextPathProp in the command line args JSONObject valueObject = props.optJSONObject(contextPathProp); if (valueObject != null) { String contextPathValue = valueObject.optString("value"); if (StringUtil.hasText(contextPathValue)) { return contextPathValue; } } } } } } } return null; } }
Added some comments on priority ordering when looking for context path
headless-services/commons/commons-boot-app-cli/src/main/java/org/springframework/ide/vscode/commons/boot/app/cli/ContextPath.java
Added some comments on priority ordering when looking for context path
Java
mpl-2.0
e9ab666be0e3a2deee05259ab334a541a5482ec7
0
Intelehealth/Android-Mobile-Client
package app.intelehealth.client.activities.patientDetailActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import androidx.appcompat.widget.Toolbar; import androidx.core.content.res.ResourcesCompat; import android.text.Html; import android.text.SpannableString; import android.text.style.BackgroundColorSpan; import android.text.style.UnderlineSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.crashlytics.android.Crashlytics; import org.apache.commons.lang3.StringUtils; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.UUID; import app.intelehealth.client.R; import app.intelehealth.client.app.AppConstants; import app.intelehealth.client.database.InteleHealthDatabaseHelper; import app.intelehealth.client.database.dao.EncounterDAO; import app.intelehealth.client.database.dao.ImagesDAO; import app.intelehealth.client.database.dao.PatientsDAO; import app.intelehealth.client.database.dao.VisitsDAO; import app.intelehealth.client.knowledgeEngine.Node; import app.intelehealth.client.models.Patient; import app.intelehealth.client.models.dto.EncounterDTO; import app.intelehealth.client.models.dto.VisitDTO; import app.intelehealth.client.utilities.DateAndTimeUtils; import app.intelehealth.client.utilities.DownloadFilesUtils; import app.intelehealth.client.utilities.FileUtils; import app.intelehealth.client.utilities.Logger; import app.intelehealth.client.utilities.SessionManager; import app.intelehealth.client.utilities.UrlModifiers; import app.intelehealth.client.utilities.UuidDictionary; import app.intelehealth.client.activities.homeActivity.HomeActivity; import app.intelehealth.client.activities.identificationActivity.IdentificationActivity; import app.intelehealth.client.activities.visitSummaryActivity.VisitSummaryActivity; import app.intelehealth.client.activities.vitalActivity.VitalsActivity; import app.intelehealth.client.utilities.NetworkConnection; import app.intelehealth.client.utilities.exception.DAOException; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.observers.DisposableObserver; import io.reactivex.schedulers.Schedulers; import okhttp3.ResponseBody; public class PatientDetailActivity extends AppCompatActivity { private static final String TAG = PatientDetailActivity.class.getSimpleName(); String patientName; String visitUuid = null; List<String> visitUuidList; String patientUuid; String intentTag = ""; String profileImage = ""; String profileImage1 = ""; SessionManager sessionManager = null; Patient patient_new = new Patient(); EncounterDTO encounterDTO = new EncounterDTO(); PatientsDAO patientsDAO = new PatientsDAO(); private boolean hasLicense = false; private boolean returning; String phistory = ""; String fhistory = ""; LinearLayout previousVisitsList; String visitValue; private String encounterVitals = ""; private String encounterAdultIntials = ""; SQLiteDatabase db = null; ImageButton editbtn; Button newVisit; IntentFilter filter; Myreceiver reMyreceive; ImageView photoView; ImagesDAO imagesDAO = new ImagesDAO(); TextView idView; String privacy_value_selected; ImageView ivPrescription; private String hasPrescription = ""; Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_patient_detail); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitleTextAppearance(this, R.style.ToolbarTheme); toolbar.setTitleTextColor(Color.WHITE); getSupportActionBar().setDisplayHomeAsUpEnabled(false); db = AppConstants.inteleHealthDatabaseHelper.getWriteDb(); sessionManager = new SessionManager(this); reMyreceive = new Myreceiver(); filter = new IntentFilter("OpenmrsID"); newVisit = findViewById(R.id.button_new_visit); context = PatientDetailActivity.this; ivPrescription = findViewById(R.id.iv_prescription); Intent intent = this.getIntent(); // The intent was passed to the activity if (intent != null) { patientUuid = intent.getStringExtra("patientUuid"); patientName = intent.getStringExtra("patientName"); hasPrescription = intent.getStringExtra("hasPrescription"); privacy_value_selected = intent.getStringExtra("privacy"); //intent value from IdentificationActivity. intentTag = intent.getStringExtra("tag"); Logger.logD(TAG, "Patient ID: " + patientUuid); Logger.logD(TAG, "Patient Name: " + patientName); Logger.logD(TAG, "Intent Tag: " + intentTag); Logger.logD(TAG, "Privacy Value on (PatientDetail): " + privacy_value_selected); } if (hasPrescription.equalsIgnoreCase("true")) { ivPrescription.setImageDrawable(getResources().getDrawable(R.drawable.ic_prescription_green)); } editbtn = findViewById(R.id.edit_button); editbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent2 = new Intent(PatientDetailActivity.this, IdentificationActivity.class); intent2.putExtra("patientUuid", patientUuid); startActivity(intent2); } }); setDisplay(patientUuid); if (newVisit.isEnabled()) { newVisit.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); newVisit.setTextColor(getResources().getColor(R.color.white)); } else { //newVisit.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark)); //newVisit.setTextColor(getResources().getColor(R.color.white)); } newVisit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // before starting, we determine if it is new visit for a returning patient // extract both FH and PMH SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault()); Date todayDate = new Date(); String thisDate = currentDate.format(todayDate); String uuid = UUID.randomUUID().toString(); EncounterDAO encounterDAO = new EncounterDAO(); encounterDTO = new EncounterDTO(); encounterDTO.setUuid(UUID.randomUUID().toString()); encounterDTO.setEncounterTypeUuid(encounterDAO.getEncounterTypeUuid("ENCOUNTER_VITALS")); encounterDTO.setEncounterTime(thisDate); encounterDTO.setVisituuid(uuid); encounterDTO.setSyncd(false); encounterDTO.setProvideruuid(sessionManager.getProviderID()); Log.d("DTO", "DTO:detail " + encounterDTO.getProvideruuid()); encounterDTO.setVoided(0); encounterDTO.setPrivacynotice_value(privacy_value_selected);//privacy value added. try { encounterDAO.createEncountersToDB(encounterDTO); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } InteleHealthDatabaseHelper mDatabaseHelper = new InteleHealthDatabaseHelper(PatientDetailActivity.this); SQLiteDatabase sqLiteDatabase = mDatabaseHelper.getReadableDatabase(); String CREATOR_ID = sessionManager.getCreatorID(); returning = false; sessionManager.setReturning(returning); String[] cols = {"value"}; Cursor cursor = sqLiteDatabase.query("tbl_obs", cols, "encounteruuid=? and conceptuuid=?",// querying for PMH new String[]{encounterDTO.getUuid(), UuidDictionary.RHK_MEDICAL_HISTORY_BLURB}, null, null, null); if (cursor.moveToFirst()) { // rows present do { // so that null data is not appended phistory = phistory + cursor.getString(0); } while (cursor.moveToNext()); returning = true; sessionManager.setReturning(returning); } cursor.close(); Cursor cursor1 = sqLiteDatabase.query("tbl_obs", cols, "encounteruuid=? and conceptuuid=?",// querying for FH new String[]{encounterDTO.getUuid(), UuidDictionary.RHK_MEDICAL_HISTORY_BLURB}, null, null, null); if (cursor1.moveToFirst()) { // rows present do { fhistory = fhistory + cursor1.getString(0); } while (cursor1.moveToNext()); returning = true; sessionManager.setReturning(returning); } cursor1.close(); // Will display data for patient as it is present in database // Toast.makeText(PatientDetailActivity.this,"PMH: "+phistory,Toast.LENGTH_SHORT).sƒhow(); // Toast.makeText(PatientDetailActivity.this,"FH: "+fhistory,Toast.LENGTH_SHORT).show(); Intent intent2 = new Intent(PatientDetailActivity.this, VitalsActivity.class); String fullName = patient_new.getFirst_name() + " " + patient_new.getLast_name(); intent2.putExtra("patientUuid", patientUuid); VisitDTO visitDTO = new VisitDTO(); visitDTO.setUuid(uuid); visitDTO.setPatientuuid(patient_new.getUuid()); visitDTO.setStartdate(thisDate); visitDTO.setVisitTypeUuid(UuidDictionary.VISIT_TELEMEDICINE); visitDTO.setLocationuuid(sessionManager.getLocationUuid()); visitDTO.setSyncd(false); visitDTO.setCreatoruuid(sessionManager.getCreatorID());//static VisitsDAO visitsDAO = new VisitsDAO(); try { visitsDAO.insertPatientToDB(visitDTO); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } // visitUuid = String.valueOf(visitLong); // localdb.close(); intent2.putExtra("patientUuid", patientUuid); intent2.putExtra("visitUuid", uuid); intent2.putExtra("encounterUuidVitals", encounterDTO.getUuid()); intent2.putExtra("encounterUuidAdultIntial", ""); intent2.putExtra("name", fullName); intent2.putExtra("tag", "new"); startActivity(intent2); } }); } @Override protected void onStart() { registerReceiver(reMyreceive, filter); super.onStart(); } @Override protected void onDestroy() { unregisterReceiver(reMyreceive); super.onDestroy(); } public void setDisplay(String dataString) { String patientSelection = "uuid = ?"; String[] patientArgs = {dataString}; String[] patientColumns = {"uuid", "openmrs_id", "first_name", "middle_name", "last_name", "date_of_birth", "address1", "address2", "city_village", "state_province", "postal_code", "country", "phone_number", "gender", "sdw", "patient_photo"}; Cursor idCursor = db.query("tbl_patient", patientColumns, patientSelection, patientArgs, null, null, null); if (idCursor.moveToFirst()) { do { patient_new.setUuid(idCursor.getString(idCursor.getColumnIndexOrThrow("uuid"))); patient_new.setOpenmrs_id(idCursor.getString(idCursor.getColumnIndexOrThrow("openmrs_id"))); patient_new.setFirst_name(idCursor.getString(idCursor.getColumnIndexOrThrow("first_name"))); patient_new.setMiddle_name(idCursor.getString(idCursor.getColumnIndexOrThrow("middle_name"))); patient_new.setLast_name(idCursor.getString(idCursor.getColumnIndexOrThrow("last_name"))); patient_new.setDate_of_birth(idCursor.getString(idCursor.getColumnIndexOrThrow("date_of_birth"))); patient_new.setAddress1(idCursor.getString(idCursor.getColumnIndexOrThrow("address1"))); patient_new.setAddress2(idCursor.getString(idCursor.getColumnIndexOrThrow("address2"))); patient_new.setCity_village(idCursor.getString(idCursor.getColumnIndexOrThrow("city_village"))); patient_new.setState_province(idCursor.getString(idCursor.getColumnIndexOrThrow("state_province"))); patient_new.setPostal_code(idCursor.getString(idCursor.getColumnIndexOrThrow("postal_code"))); patient_new.setCountry(idCursor.getString(idCursor.getColumnIndexOrThrow("country"))); patient_new.setPhone_number(idCursor.getString(idCursor.getColumnIndexOrThrow("phone_number"))); patient_new.setGender(idCursor.getString(idCursor.getColumnIndexOrThrow("gender"))); patient_new.setPatient_photo(idCursor.getString(idCursor.getColumnIndexOrThrow("patient_photo"))); } while (idCursor.moveToNext()); } idCursor.close(); String patientSelection1 = "patientuuid = ?"; String[] patientArgs1 = {dataString}; String[] patientColumns1 = {"value", "person_attribute_type_uuid"}; Cursor idCursor1 = db.query("tbl_patient_attribute", patientColumns1, patientSelection1, patientArgs1, null, null, null); String name = ""; if (idCursor1.moveToFirst()) { do { try { name = patientsDAO.getAttributesName(idCursor1.getString(idCursor1.getColumnIndexOrThrow("person_attribute_type_uuid"))); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } if (name.equalsIgnoreCase("caste")) { patient_new.setCaste(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("Telephone Number")) { patient_new.setPhone_number(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("Education Level")) { patient_new.setEducation_level(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("Economic Status")) { patient_new.setEconomic_status(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("occupation")) { patient_new.setOccupation(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("Son/wife/daughter")) { patient_new.setSdw(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("ProfileImageTimestamp")) { profileImage1 = idCursor1.getString(idCursor1.getColumnIndexOrThrow("value")); } } while (idCursor1.moveToNext()); } idCursor1.close(); photoView = findViewById(R.id.imageView_patient); idView = findViewById(R.id.textView_ID); TextView patinetName = findViewById(R.id.textView_name); TextView dobView = findViewById(R.id.textView_DOB); TextView ageView = findViewById(R.id.textView_age); TextView addr1View = findViewById(R.id.textView_address_1); TableRow addr2Row = findViewById(R.id.tableRow_addr2); TextView addr2View = findViewById(R.id.textView_address2); TextView addrFinalView = findViewById(R.id.textView_address_final); TextView casteView = findViewById(R.id.textView_caste); TextView economic_statusView = findViewById(R.id.textView_economic_status); TextView education_statusView = findViewById(R.id.textView_education_status); TextView phoneView = findViewById(R.id.textView_phone); TextView sdwView = findViewById(R.id.textView_SDW); TableRow sdwRow = findViewById(R.id.tableRow_SDW); TextView occuView = findViewById(R.id.textView_occupation); TableRow occuRow = findViewById(R.id.tableRow_Occupation); TableRow economicRow = findViewById(R.id.tableRow_Economic_Status); TableRow educationRow = findViewById(R.id.tableRow_Education_Status); TableRow casteRow = findViewById(R.id.tableRow_Caste); TextView medHistView = findViewById(R.id.textView_patHist); TextView famHistView = findViewById(R.id.textView_famHist); if (!sessionManager.getLicenseKey().isEmpty()) { hasLicense = true; } try { JSONObject obj = null; if (hasLicense) { obj = new JSONObject(FileUtils.readFileRoot(AppConstants.CONFIG_FILE_NAME, this)); //Load the config file } else { obj = new JSONObject(String.valueOf(FileUtils.encodeJSON(this, AppConstants.CONFIG_FILE_NAME))); } //Display the fields on the Add Patient screen as per the config file if (obj.getBoolean("casteLayout")) { casteRow.setVisibility(View.VISIBLE); } else { casteRow.setVisibility(View.GONE); } if (obj.getBoolean("educationLayout")) { educationRow.setVisibility(View.VISIBLE); } else { educationRow.setVisibility(View.GONE); } if (obj.getBoolean("economicLayout")) { economicRow.setVisibility(View.VISIBLE); } else { economicRow.setVisibility(View.GONE); } } catch (JSONException e) { Crashlytics.getInstance().core.logException(e); // Issue #627 // added the catch exception to check the config and throwing back to setup activity Toast.makeText(getApplicationContext(), "JsonException" + e, Toast.LENGTH_LONG).show(); // showAlertDialogButtonClicked(e.toString()); } //changing patient to patient_new object if (patient_new.getMiddle_name() == null) { patientName = patient_new.getFirst_name() + " " + patient_new.getLast_name(); } else { patientName = patient_new.getFirst_name() + " " + patient_new.getMiddle_name() + " " + patient_new.getLast_name(); } // setTitle(patientName); patinetName.setText(patientName); try { profileImage = imagesDAO.getPatientProfileChangeTime(patientUuid); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } if (patient_new.getPatient_photo() == null || patient_new.getPatient_photo().equalsIgnoreCase("")) { if (NetworkConnection.isOnline(getApplication())) { profilePicDownloaded(); } } if (!profileImage.equalsIgnoreCase(profileImage1)) { if (NetworkConnection.isOnline(getApplication())) { profilePicDownloaded(); } } Glide.with(PatientDetailActivity.this) .load(patient_new.getPatient_photo()) .thumbnail(0.3f) .centerCrop() .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .into(photoView); if (patient_new.getOpenmrs_id() != null && !patient_new.getOpenmrs_id().isEmpty()) { idView.setText(patient_new.getOpenmrs_id()); // sessionManager.setOfllineOpenMRSID(patient_new.getOpenmrs_id()); } else { idView.setText(getString(R.string.patient_not_registered)); } // if (!NetworkConnection.isOnline(getApplication())) { // if (!sessionManager.getOfllineOpenMRSID().equals("")) { // idView.setText(sessionManager.getOfllineOpenMRSID()); // } else { // idView.setText(getString(R.string.patient_not_registered)); // } // } setTitle(patient_new.getOpenmrs_id()); //String id = idView.toString(); //Log.d("IDEA","IDEA"+id); String age = DateAndTimeUtils.getAgeInYearMonth(patient_new.getDate_of_birth(), context); ageView.setText(age); String dob = DateAndTimeUtils.getFormatedDateOfBirthAsView(patient_new.getDate_of_birth()); dobView.setText(dob); if (patient_new.getAddress1() == null || patient_new.getAddress1().equals("")) { addr1View.setVisibility(View.GONE); } else { addr1View.setText(patient_new.getAddress1()); } if (patient_new.getAddress2() == null || patient_new.getAddress2().equals("")) { addr2Row.setVisibility(View.GONE); } else { addr2View.setText(patient_new.getAddress2()); } String city_village; if (patient_new.getCity_village() != null) { city_village = patient_new.getCity_village().trim(); } else { city_village = ""; } String postal_code; if (patient_new.getPostal_code() != null) { postal_code = patient_new.getPostal_code().trim() + ","; } else { postal_code = ""; } String addrFinalLine = String.format("%s, %s, %s %s", city_village, patient_new.getState_province(), postal_code, patient_new.getCountry()); addrFinalView.setText(addrFinalLine); phoneView.setText(patient_new.getPhone_number()); education_statusView.setText(patient_new.getEducation_level()); economic_statusView.setText(patient_new.getEconomic_status()); casteView.setText(patient_new.getCaste()); // if (patient_new.getSdw() != null && !patient_new.getSdw().equals("")) { sdwView.setText(patient_new.getSdw()); } else { sdwRow.setVisibility(View.GONE); } // if (patient_new.getOccupation() != null && !patient_new.getOccupation().equals("")) { occuView.setText(patient_new.getOccupation()); } else { occuRow.setVisibility(View.GONE); } if (visitUuid != null && !visitUuid.isEmpty()) { CardView histCardView = findViewById(R.id.cardView_history); histCardView.setVisibility(View.GONE); } else { visitUuidList = new ArrayList<>(); String visitIDSelection = "patientuuid = ?"; String[] visitIDArgs = {patientUuid}; Cursor visitIDCursor = db.query("tbl_visit", null, visitIDSelection, visitIDArgs, null, null, null); if (visitIDCursor != null && visitIDCursor.moveToFirst()) { do { visitUuid = visitIDCursor.getString(visitIDCursor.getColumnIndexOrThrow("uuid")); visitUuidList.add(visitUuid); } while (visitIDCursor.moveToNext()); } if (visitIDCursor != null) { visitIDCursor.close(); } for (String visituuid : visitUuidList) { Logger.logD(TAG, visituuid); EncounterDAO encounterDAO = new EncounterDAO(); String encounterIDSelection = "visituuid = ?"; String[] encounterIDArgs = {visituuid}; Cursor encounterCursor = db.query("tbl_encounter", null, encounterIDSelection, encounterIDArgs, null, null, null); if (encounterCursor != null && encounterCursor.moveToFirst()) { do { if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_VITALS").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encounterVitals = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_ADULTINITIAL").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encounterAdultIntials = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } } while (encounterCursor.moveToNext()); } encounterCursor.close(); } familyHistory(famHistView, patientUuid); pastMedicalHistory(medHistView, patientUuid); pastVisits(patientUuid); } } public void profilePicDownloaded() { UrlModifiers urlModifiers = new UrlModifiers(); String url = urlModifiers.patientProfileImageUrl(patientUuid); Logger.logD(TAG, "profileimage url" + url); Observable<ResponseBody> profilePicDownload = AppConstants.apiInterface.PERSON_PROFILE_PIC_DOWNLOAD(url, "Basic " + sessionManager.getEncoded()); profilePicDownload.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new DisposableObserver<ResponseBody>() { @Override public void onNext(ResponseBody file) { DownloadFilesUtils downloadFilesUtils = new DownloadFilesUtils(); downloadFilesUtils.saveToDisk(file, patientUuid); Logger.logD(TAG, file.toString()); } @Override public void onError(Throwable e) { Logger.logD(TAG, e.getMessage()); } @Override public void onComplete() { Logger.logD(TAG, "complete" + patient_new.getPatient_photo()); PatientsDAO patientsDAO = new PatientsDAO(); boolean updated = false; try { updated = patientsDAO.updatePatientPhoto(patientUuid, AppConstants.IMAGE_PATH + patientUuid + ".jpg"); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } if (updated) { Glide.with(PatientDetailActivity.this) .load(AppConstants.IMAGE_PATH + patientUuid + ".jpg") .thumbnail(0.3f) .centerCrop() .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .into(photoView); } ImagesDAO imagesDAO = new ImagesDAO(); boolean isImageDownloaded = false; try { isImageDownloaded = imagesDAO.insertPatientProfileImages(AppConstants.IMAGE_PATH + patientUuid + ".jpg", patientUuid); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } // if (isImageDownloaded) // AppConstants.notificationUtils.DownloadDone(getString(R.string.patient_image_download_notifi), "" + patient_new.getFirst_name() + "" + patient_new.getLast_name() + "'s Image Download Incomplete.", 4, getApplication()); // else // AppConstants.notificationUtils.DownloadDone(getString(R.string.patient_image_download_notifi), "" + patient_new.getFirst_name() + "" + patient_new.getLast_name() + "'s Image Download Incomplete.", 4, getApplication()); } }); } /** * This method retrieves details about patient's old visits. * * @param datetime variable of type String. * @return void */ private void createOldVisit(final String datetime, String visit_id, String end_datetime, String visitValue, String encounterVitalslocal, String encounterAdultIntialslocal) throws ParseException { final Boolean past_visit; final TextView textView = new TextView(this); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); final String visitString = String.format("Seen on (%s)", DateAndTimeUtils.SimpleDatetoLongDate(datetime)); if (end_datetime == null || end_datetime.isEmpty()) { // visit has not yet ended for (int i = 1; i <= 2; i++) { if (i == 1) { SpannableString spannableString = new SpannableString(visitString + " Active"); Object greenSpan = new BackgroundColorSpan(Color.GREEN); Object underlineSpan = new UnderlineSpan(); spannableString.setSpan(greenSpan, spannableString.length() - 6, spannableString.length(), 0); spannableString.setSpan(underlineSpan, 0, spannableString.length() - 7, 0); textView.setText(spannableString); layoutParams.setMargins(5, 10, 5, 0); // textView.setLayoutParams(layoutParams); textView.setTextSize(16); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); textView.setTypeface(typeface); previousVisitsList.addView(textView); } //If patient come up with any complaints if (i == 2) { TextView complaintxt1 = new TextView(this); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); complaintxt1.setTypeface(typeface); complaintxt1.setLayoutParams(layoutParams); if (visitValue != null && !visitValue.equals("")) { String visitComplaint = Html.fromHtml(visitValue).toString(); complaintxt1.setText(visitComplaint.replace("\n" + Node.bullet_arrow + "Associated symptoms", "")); } else { Log.e("Check", "No complaint"); } layoutParams.setMargins(5, 10, 5, 0); //complaintxt1.setLayoutParams(layoutParams); complaintxt1.setTextSize(16); previousVisitsList.addView(complaintxt1); } } past_visit = false; if (newVisit.isEnabled()) { newVisit.setEnabled(false); } if (newVisit.isClickable()) { newVisit.setClickable(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { newVisit.setBackgroundColor (getColor(R.color.divider)); newVisit.setTextColor(getColor(R.color.white)); } else { newVisit.setBackgroundColor(getResources().getColor(R.color.divider)); newVisit.setTextColor(getResources().getColor(R.color.white)); } } } else { // when visit has ended past_visit = true; for (int i = 1; i <= 2; i++) { if (i == 1) { textView.setText(visitString); textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); textView.setTypeface(typeface); textView.setTextSize(16); layoutParams.setMargins(5, 10, 5, 0); // textView.setLayoutParams(layoutParams); previousVisitsList.addView(textView); } //If patient has any past complaints if (i == 2) { TextView complaintxt1 = new TextView(this); if (visitValue != null && !visitValue.equals("")) { String visitComplaint = Html.fromHtml(visitValue).toString(); complaintxt1.setText(visitComplaint.replace("\n" + Node.bullet_arrow + "Associated symptoms", "")); } else { Log.e("Check", "No complaint"); } layoutParams.setMargins(5, 10, 5, 0); // complaintxt1.setLayoutParams(layoutParams); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); complaintxt1.setTypeface(typeface); complaintxt1.setTextSize(16); previousVisitsList.addView(complaintxt1); } } } textView.setTextSize(16); LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); llp.setMargins(0, 10, 0, 0); // textView.setLayoutParams(llp); textView.setTag(visit_id); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); textView.setTypeface(typeface); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // int position = (Integer) v.getTag(); Intent visitSummary = new Intent(PatientDetailActivity.this, VisitSummaryActivity.class); visitSummary.putExtra("visitUuid", visit_id); visitSummary.putExtra("patientUuid", patientUuid); visitSummary.putExtra("encounterUuidVitals", encounterVitalslocal); visitSummary.putExtra("encounterUuidAdultIntial", encounterAdultIntialslocal); visitSummary.putExtra("name", patientName); visitSummary.putExtra("tag", intentTag); visitSummary.putExtra("pastVisit", past_visit); if (hasPrescription.equalsIgnoreCase("true")) { visitSummary.putExtra("hasPrescription", "true"); } else { visitSummary.putExtra("hasPrescription", "false"); } startActivity(visitSummary); } }); //previousVisitsList.addView(textView); //TODO: add on click listener to open the previous visit } /** * This method is called when patient has no prior visits. * * @return void */ private void neverSeen() { final LayoutInflater inflater = PatientDetailActivity.this.getLayoutInflater(); View convertView = inflater.inflate(R.layout.list_item_previous_visit, null); TextView textView = convertView.findViewById(R.id.textView_visit_info); String visitString = getString(R.string.no_prior_visits); textView.setText(visitString); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); textView.setTypeface(typeface); textView.setTextSize(16); previousVisitsList.addView(convertView); } @Override public void onBackPressed() { Intent i = new Intent(this, HomeActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); } public class Myreceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { idView.setText(patientsDAO.getOpenmrsId(patientUuid)); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } setTitle(idView.getText()); } } public void familyHistory(TextView famHistView, String patientuuid) { String visitSelection = "patientuuid = ? AND enddate IS NULL OR enddate = ''"; String[] visitArgs = {patientuuid}; String[] visitColumns = {"uuid, startdate", "enddate"}; String visitOrderBy = "startdate"; Cursor visitCursor = db.query("tbl_visit", visitColumns, visitSelection, visitArgs, null, null, visitOrderBy); previousVisitsList = findViewById(R.id.linearLayout_previous_visits); if (visitCursor.getCount() < 1) { // neverSeen(); } else { if (visitCursor.moveToLast() && visitCursor != null) { do { EncounterDAO encounterDAO = new EncounterDAO(); String date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("startdate")); String end_date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("enddate")); String visit_id = visitCursor.getString(visitCursor.getColumnIndexOrThrow("uuid")); String encounterlocalAdultintial = ""; String encountervitalsLocal = null; String encounterIDSelection = "visituuid = ?"; String[] encounterIDArgs = {visit_id}; Cursor encounterCursor = db.query("tbl_encounter", null, encounterIDSelection, encounterIDArgs, null, null, null); if (encounterCursor != null && encounterCursor.moveToFirst()) { do { if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_VITALS").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encountervitalsLocal = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_ADULTINITIAL").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encounterlocalAdultintial = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } } while (encounterCursor.moveToNext()); } if (encounterCursor != null) { encounterCursor.close(); } String famHistSelection = "encounteruuid = ? AND conceptuuid = ? And voided!='1'"; String[] famHistArgs = {encounterlocalAdultintial, UuidDictionary.RHK_FAMILY_HISTORY_BLURB}; String[] famHistColumns = {"value", " conceptuuid"}; Cursor famHistCursor = db.query("tbl_obs", famHistColumns, famHistSelection, famHistArgs, null, null, null); famHistCursor.moveToLast(); String famHistValue; try { famHistValue = famHistCursor.getString(famHistCursor.getColumnIndexOrThrow("value")); } catch (Exception e) { famHistValue = ""; } finally { famHistCursor.close(); } if (famHistValue != null && !famHistValue.equals("")) { famHistView.setText(Html.fromHtml(famHistValue)); } else { famHistView.setText(getString(R.string.string_no_hist)); } } while (visitCursor.moveToPrevious()); } visitCursor.close(); } } public void pastMedicalHistory(TextView medHistView, String patientuuid) { String visitSelection = "patientuuid = ? AND enddate IS NULL OR enddate = ''"; String[] visitArgs = {patientuuid}; String[] visitColumns = {"uuid, startdate", "enddate"}; String visitOrderBy = "startdate"; Cursor visitCursor = db.query("tbl_visit", visitColumns, visitSelection, visitArgs, null, null, visitOrderBy); previousVisitsList = findViewById(R.id.linearLayout_previous_visits); if (visitCursor.getCount() < 1) { // neverSeen(); } else { if (visitCursor.moveToLast() && visitCursor != null) { do { EncounterDAO encounterDAO = new EncounterDAO(); String date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("startdate")); String end_date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("enddate")); String visit_id = visitCursor.getString(visitCursor.getColumnIndexOrThrow("uuid")); String encounterlocalAdultintial = ""; String encountervitalsLocal = null; String encounterIDSelection = "visituuid = ?"; String[] encounterIDArgs = {visit_id}; Cursor encounterCursor = db.query("tbl_encounter", null, encounterIDSelection, encounterIDArgs, null, null, null); if (encounterCursor != null && encounterCursor.moveToFirst()) { do { if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_VITALS").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encountervitalsLocal = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_ADULTINITIAL").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encounterlocalAdultintial = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } } while (encounterCursor.moveToNext()); } if (encounterCursor != null) { encounterCursor.close(); } String medHistSelection = "encounteruuid = ? AND conceptuuid = ? And voided!='1'"; String[] medHistArgs = {encounterlocalAdultintial, UuidDictionary.RHK_MEDICAL_HISTORY_BLURB}; String[] medHistColumms = {"value", " conceptuuid"}; Cursor medHistCursor = db.query("tbl_obs", medHistColumms, medHistSelection, medHistArgs, null, null, null); medHistCursor.moveToLast(); String medHistValue; try { medHistValue = medHistCursor.getString(medHistCursor.getColumnIndexOrThrow("value")); } catch (Exception e) { medHistValue = ""; } finally { medHistCursor.close(); } if (medHistValue != null && !medHistValue.equals("")) { medHistView.setText(Html.fromHtml(medHistValue)); } else { medHistView.setText(getString(R.string.string_no_hist)); } } while (visitCursor.moveToPrevious()); } visitCursor.close(); } } public void pastVisits(String patientuuid) { String visitSelection = "patientuuid = ?"; String[] visitArgs = {patientuuid}; String[] visitColumns = {"uuid, startdate", "enddate"}; String visitOrderBy = "startdate"; Cursor visitCursor = db.query("tbl_visit", visitColumns, visitSelection, visitArgs, null, null, visitOrderBy); previousVisitsList = findViewById(R.id.linearLayout_previous_visits); if (visitCursor.getCount() < 1) { neverSeen(); } else { if (visitCursor.moveToLast() && visitCursor != null) { do { EncounterDAO encounterDAO = new EncounterDAO(); String date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("startdate")); String end_date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("enddate")); String visit_id = visitCursor.getString(visitCursor.getColumnIndexOrThrow("uuid")); String encounterlocalAdultintial = ""; String encountervitalsLocal = null; String encounterIDSelection = "visituuid = ?"; String[] encounterIDArgs = {visit_id}; Cursor encounterCursor = db.query("tbl_encounter", null, encounterIDSelection, encounterIDArgs, null, null, null); if (encounterCursor != null && encounterCursor.moveToFirst()) { do { if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_VITALS").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encountervitalsLocal = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_ADULTINITIAL").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encounterlocalAdultintial = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } } while (encounterCursor.moveToNext()); } encounterCursor.close(); String previsitSelection = "encounteruuid = ? AND conceptuuid = ? and voided !='1'"; String[] previsitArgs = {encounterlocalAdultintial, UuidDictionary.CURRENT_COMPLAINT}; String[] previsitColumms = {"value", " conceptuuid", "encounteruuid"}; Cursor previsitCursor = db.query("tbl_obs", previsitColumms, previsitSelection, previsitArgs, null, null, null); if (previsitCursor.moveToLast() && previsitCursor != null) { String visitValue = previsitCursor.getString(previsitCursor.getColumnIndexOrThrow("value")); if (visitValue != null && !visitValue.isEmpty()) { visitValue = visitValue.replace("?<b>",Node.bullet_arrow); String[] complaints = StringUtils.split(visitValue, Node.bullet_arrow); visitValue = ""; String colon = ":"; if (complaints != null) { for (String comp : complaints) { if (!comp.trim().isEmpty()) { visitValue = visitValue + Node.bullet_arrow + comp.substring(0, comp.indexOf(colon)) + "<br/>"; } } if (!visitValue.isEmpty()) { visitValue = visitValue.substring(0, visitValue.length() - 2); visitValue = visitValue.replaceAll("<b>", ""); visitValue = visitValue.replaceAll("</b>", ""); } SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); try { Date formatted = currentDate.parse(date); String visitDate = currentDate.format(formatted); createOldVisit(visitDate, visit_id, end_date, visitValue, encountervitalsLocal, encounterlocalAdultintial); } catch (ParseException e) { Crashlytics.getInstance().core.logException(e); } } } // Called when we select complaints but not select any sub knowledgeEngine inside that complaint else { SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); try { Date formatted = currentDate.parse(date); String visitDate = currentDate.format(formatted); createOldVisit(visitDate, visit_id, end_date, visitValue, encountervitalsLocal, encounterlocalAdultintial); } catch (ParseException e) { Crashlytics.getInstance().core.logException(e); } } } // Called when we close app on vitals screen and Didn't select any complaints else { SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); try { Date formatted = currentDate.parse(date); String visitDate = currentDate.format(formatted); createOldVisit(visitDate, visit_id, end_date, visitValue, encountervitalsLocal, encounterlocalAdultintial); } catch (ParseException e) { Crashlytics.getInstance().core.logException(e); } } } while (visitCursor.moveToPrevious()); } } visitCursor.close(); } @Override protected void onStop() { super.onStop(); } public boolean onCreateOptionsMenu(Menu menu) { // Inflate the options menu from XML MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.detail_home: Intent intent = new Intent(PatientDetailActivity.this, HomeActivity.class); //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } }
app/src/main/java/app/intelehealth/client/activities/patientDetailActivity/PatientDetailActivity.java
package app.intelehealth.client.activities.patientDetailActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import androidx.appcompat.widget.Toolbar; import androidx.core.content.res.ResourcesCompat; import android.text.Html; import android.text.SpannableString; import android.text.style.BackgroundColorSpan; import android.text.style.UnderlineSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.crashlytics.android.Crashlytics; import org.apache.commons.lang3.StringUtils; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.UUID; import app.intelehealth.client.R; import app.intelehealth.client.app.AppConstants; import app.intelehealth.client.database.InteleHealthDatabaseHelper; import app.intelehealth.client.database.dao.EncounterDAO; import app.intelehealth.client.database.dao.ImagesDAO; import app.intelehealth.client.database.dao.PatientsDAO; import app.intelehealth.client.database.dao.VisitsDAO; import app.intelehealth.client.knowledgeEngine.Node; import app.intelehealth.client.models.Patient; import app.intelehealth.client.models.dto.EncounterDTO; import app.intelehealth.client.models.dto.VisitDTO; import app.intelehealth.client.utilities.DateAndTimeUtils; import app.intelehealth.client.utilities.DownloadFilesUtils; import app.intelehealth.client.utilities.FileUtils; import app.intelehealth.client.utilities.Logger; import app.intelehealth.client.utilities.SessionManager; import app.intelehealth.client.utilities.UrlModifiers; import app.intelehealth.client.utilities.UuidDictionary; import app.intelehealth.client.activities.homeActivity.HomeActivity; import app.intelehealth.client.activities.identificationActivity.IdentificationActivity; import app.intelehealth.client.activities.visitSummaryActivity.VisitSummaryActivity; import app.intelehealth.client.activities.vitalActivity.VitalsActivity; import app.intelehealth.client.utilities.NetworkConnection; import app.intelehealth.client.utilities.exception.DAOException; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.observers.DisposableObserver; import io.reactivex.schedulers.Schedulers; import okhttp3.ResponseBody; public class PatientDetailActivity extends AppCompatActivity { private static final String TAG = PatientDetailActivity.class.getSimpleName(); String patientName; String visitUuid = null; List<String> visitUuidList; String patientUuid; String intentTag = ""; String profileImage = ""; String profileImage1 = ""; SessionManager sessionManager = null; Patient patient_new = new Patient(); EncounterDTO encounterDTO = new EncounterDTO(); PatientsDAO patientsDAO = new PatientsDAO(); private boolean hasLicense = false; private boolean returning; String phistory = ""; String fhistory = ""; LinearLayout previousVisitsList; String visitValue; private String encounterVitals = ""; private String encounterAdultIntials = ""; SQLiteDatabase db = null; ImageButton editbtn; Button newVisit; IntentFilter filter; Myreceiver reMyreceive; ImageView photoView; ImagesDAO imagesDAO = new ImagesDAO(); TextView idView; String privacy_value_selected; ImageView ivPrescription; private String hasPrescription = ""; Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_patient_detail); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitleTextAppearance(this, R.style.ToolbarTheme); toolbar.setTitleTextColor(Color.WHITE); getSupportActionBar().setDisplayHomeAsUpEnabled(false); db = AppConstants.inteleHealthDatabaseHelper.getWriteDb(); sessionManager = new SessionManager(this); reMyreceive = new Myreceiver(); filter = new IntentFilter("OpenmrsID"); newVisit = findViewById(R.id.button_new_visit); context = PatientDetailActivity.this; ivPrescription = findViewById(R.id.iv_prescription); Intent intent = this.getIntent(); // The intent was passed to the activity if (intent != null) { patientUuid = intent.getStringExtra("patientUuid"); patientName = intent.getStringExtra("patientName"); hasPrescription = intent.getStringExtra("hasPrescription"); privacy_value_selected = intent.getStringExtra("privacy"); //intent value from IdentificationActivity. intentTag = intent.getStringExtra("tag"); Logger.logD(TAG, "Patient ID: " + patientUuid); Logger.logD(TAG, "Patient Name: " + patientName); Logger.logD(TAG, "Intent Tag: " + intentTag); Logger.logD(TAG, "Privacy Value on (PatientDetail): " + privacy_value_selected); } if (hasPrescription.equalsIgnoreCase("true")) { ivPrescription.setImageDrawable(getResources().getDrawable(R.drawable.ic_prescription_green)); } editbtn = findViewById(R.id.edit_button); editbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent2 = new Intent(PatientDetailActivity.this, IdentificationActivity.class); intent2.putExtra("patientUuid", patientUuid); startActivity(intent2); } }); setDisplay(patientUuid); if (newVisit.isEnabled()) { newVisit.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); newVisit.setTextColor(getResources().getColor(R.color.white)); } else { //newVisit.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark)); //newVisit.setTextColor(getResources().getColor(R.color.white)); } newVisit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // before starting, we determine if it is new visit for a returning patient // extract both FH and PMH SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault()); Date todayDate = new Date(); String thisDate = currentDate.format(todayDate); String uuid = UUID.randomUUID().toString(); EncounterDAO encounterDAO = new EncounterDAO(); encounterDTO = new EncounterDTO(); encounterDTO.setUuid(UUID.randomUUID().toString()); encounterDTO.setEncounterTypeUuid(encounterDAO.getEncounterTypeUuid("ENCOUNTER_VITALS")); encounterDTO.setEncounterTime(thisDate); encounterDTO.setVisituuid(uuid); encounterDTO.setSyncd(false); encounterDTO.setProvideruuid(sessionManager.getProviderID()); Log.d("DTO", "DTO:detail " + encounterDTO.getProvideruuid()); encounterDTO.setVoided(0); encounterDTO.setPrivacynotice_value(privacy_value_selected);//privacy value added. try { encounterDAO.createEncountersToDB(encounterDTO); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } InteleHealthDatabaseHelper mDatabaseHelper = new InteleHealthDatabaseHelper(PatientDetailActivity.this); SQLiteDatabase sqLiteDatabase = mDatabaseHelper.getReadableDatabase(); String CREATOR_ID = sessionManager.getCreatorID(); returning = false; sessionManager.setReturning(returning); String[] cols = {"value"}; Cursor cursor = sqLiteDatabase.query("tbl_obs", cols, "encounteruuid=? and conceptuuid=?",// querying for PMH new String[]{encounterDTO.getUuid(), UuidDictionary.RHK_MEDICAL_HISTORY_BLURB}, null, null, null); if (cursor.moveToFirst()) { // rows present do { // so that null data is not appended phistory = phistory + cursor.getString(0); } while (cursor.moveToNext()); returning = true; sessionManager.setReturning(returning); } cursor.close(); Cursor cursor1 = sqLiteDatabase.query("tbl_obs", cols, "encounteruuid=? and conceptuuid=?",// querying for FH new String[]{encounterDTO.getUuid(), UuidDictionary.RHK_MEDICAL_HISTORY_BLURB}, null, null, null); if (cursor1.moveToFirst()) { // rows present do { fhistory = fhistory + cursor1.getString(0); } while (cursor1.moveToNext()); returning = true; sessionManager.setReturning(returning); } cursor1.close(); // Will display data for patient as it is present in database // Toast.makeText(PatientDetailActivity.this,"PMH: "+phistory,Toast.LENGTH_SHORT).sƒhow(); // Toast.makeText(PatientDetailActivity.this,"FH: "+fhistory,Toast.LENGTH_SHORT).show(); Intent intent2 = new Intent(PatientDetailActivity.this, VitalsActivity.class); String fullName = patient_new.getFirst_name() + " " + patient_new.getLast_name(); intent2.putExtra("patientUuid", patientUuid); VisitDTO visitDTO = new VisitDTO(); visitDTO.setUuid(uuid); visitDTO.setPatientuuid(patient_new.getUuid()); visitDTO.setStartdate(thisDate); visitDTO.setVisitTypeUuid(UuidDictionary.VISIT_TELEMEDICINE); visitDTO.setLocationuuid(sessionManager.getLocationUuid()); visitDTO.setSyncd(false); visitDTO.setCreatoruuid(sessionManager.getCreatorID());//static VisitsDAO visitsDAO = new VisitsDAO(); try { visitsDAO.insertPatientToDB(visitDTO); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } // visitUuid = String.valueOf(visitLong); // localdb.close(); intent2.putExtra("patientUuid", patientUuid); intent2.putExtra("visitUuid", uuid); intent2.putExtra("encounterUuidVitals", encounterDTO.getUuid()); intent2.putExtra("encounterUuidAdultIntial", ""); intent2.putExtra("name", fullName); intent2.putExtra("tag", "new"); startActivity(intent2); } }); } @Override protected void onStart() { registerReceiver(reMyreceive, filter); super.onStart(); } @Override protected void onDestroy() { unregisterReceiver(reMyreceive); super.onDestroy(); } public void setDisplay(String dataString) { String patientSelection = "uuid = ?"; String[] patientArgs = {dataString}; String[] patientColumns = {"uuid", "openmrs_id", "first_name", "middle_name", "last_name", "date_of_birth", "address1", "address2", "city_village", "state_province", "postal_code", "country", "phone_number", "gender", "sdw", "patient_photo"}; Cursor idCursor = db.query("tbl_patient", patientColumns, patientSelection, patientArgs, null, null, null); if (idCursor.moveToFirst()) { do { patient_new.setUuid(idCursor.getString(idCursor.getColumnIndexOrThrow("uuid"))); patient_new.setOpenmrs_id(idCursor.getString(idCursor.getColumnIndexOrThrow("openmrs_id"))); patient_new.setFirst_name(idCursor.getString(idCursor.getColumnIndexOrThrow("first_name"))); patient_new.setMiddle_name(idCursor.getString(idCursor.getColumnIndexOrThrow("middle_name"))); patient_new.setLast_name(idCursor.getString(idCursor.getColumnIndexOrThrow("last_name"))); patient_new.setDate_of_birth(idCursor.getString(idCursor.getColumnIndexOrThrow("date_of_birth"))); patient_new.setAddress1(idCursor.getString(idCursor.getColumnIndexOrThrow("address1"))); patient_new.setAddress2(idCursor.getString(idCursor.getColumnIndexOrThrow("address2"))); patient_new.setCity_village(idCursor.getString(idCursor.getColumnIndexOrThrow("city_village"))); patient_new.setState_province(idCursor.getString(idCursor.getColumnIndexOrThrow("state_province"))); patient_new.setPostal_code(idCursor.getString(idCursor.getColumnIndexOrThrow("postal_code"))); patient_new.setCountry(idCursor.getString(idCursor.getColumnIndexOrThrow("country"))); patient_new.setPhone_number(idCursor.getString(idCursor.getColumnIndexOrThrow("phone_number"))); patient_new.setGender(idCursor.getString(idCursor.getColumnIndexOrThrow("gender"))); patient_new.setPatient_photo(idCursor.getString(idCursor.getColumnIndexOrThrow("patient_photo"))); } while (idCursor.moveToNext()); } idCursor.close(); String patientSelection1 = "patientuuid = ?"; String[] patientArgs1 = {dataString}; String[] patientColumns1 = {"value", "person_attribute_type_uuid"}; Cursor idCursor1 = db.query("tbl_patient_attribute", patientColumns1, patientSelection1, patientArgs1, null, null, null); String name = ""; if (idCursor1.moveToFirst()) { do { try { name = patientsDAO.getAttributesName(idCursor1.getString(idCursor1.getColumnIndexOrThrow("person_attribute_type_uuid"))); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } if (name.equalsIgnoreCase("caste")) { patient_new.setCaste(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("Telephone Number")) { patient_new.setPhone_number(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("Education Level")) { patient_new.setEducation_level(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("Economic Status")) { patient_new.setEconomic_status(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("occupation")) { patient_new.setOccupation(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("Son/wife/daughter")) { patient_new.setSdw(idCursor1.getString(idCursor1.getColumnIndexOrThrow("value"))); } if (name.equalsIgnoreCase("ProfileImageTimestamp")) { profileImage1 = idCursor1.getString(idCursor1.getColumnIndexOrThrow("value")); } } while (idCursor1.moveToNext()); } idCursor1.close(); photoView = findViewById(R.id.imageView_patient); idView = findViewById(R.id.textView_ID); TextView patinetName = findViewById(R.id.textView_name); TextView dobView = findViewById(R.id.textView_DOB); TextView ageView = findViewById(R.id.textView_age); TextView addr1View = findViewById(R.id.textView_address_1); TableRow addr2Row = findViewById(R.id.tableRow_addr2); TextView addr2View = findViewById(R.id.textView_address2); TextView addrFinalView = findViewById(R.id.textView_address_final); TextView casteView = findViewById(R.id.textView_caste); TextView economic_statusView = findViewById(R.id.textView_economic_status); TextView education_statusView = findViewById(R.id.textView_education_status); TextView phoneView = findViewById(R.id.textView_phone); TextView sdwView = findViewById(R.id.textView_SDW); TableRow sdwRow = findViewById(R.id.tableRow_SDW); TextView occuView = findViewById(R.id.textView_occupation); TableRow occuRow = findViewById(R.id.tableRow_Occupation); TableRow economicRow = findViewById(R.id.tableRow_Economic_Status); TableRow educationRow = findViewById(R.id.tableRow_Education_Status); TableRow casteRow = findViewById(R.id.tableRow_Caste); TextView medHistView = findViewById(R.id.textView_patHist); TextView famHistView = findViewById(R.id.textView_famHist); if (!sessionManager.getLicenseKey().isEmpty()) { hasLicense = true; } try { JSONObject obj = null; if (hasLicense) { obj = new JSONObject(FileUtils.readFileRoot(AppConstants.CONFIG_FILE_NAME, this)); //Load the config file } else { obj = new JSONObject(String.valueOf(FileUtils.encodeJSON(this, AppConstants.CONFIG_FILE_NAME))); } //Display the fields on the Add Patient screen as per the config file if (obj.getBoolean("casteLayout")) { casteRow.setVisibility(View.VISIBLE); } else { casteRow.setVisibility(View.GONE); } if (obj.getBoolean("educationLayout")) { educationRow.setVisibility(View.VISIBLE); } else { educationRow.setVisibility(View.GONE); } if (obj.getBoolean("economicLayout")) { economicRow.setVisibility(View.VISIBLE); } else { economicRow.setVisibility(View.GONE); } } catch (JSONException e) { Crashlytics.getInstance().core.logException(e); // Issue #627 // added the catch exception to check the config and throwing back to setup activity Toast.makeText(getApplicationContext(), "JsonException" + e, Toast.LENGTH_LONG).show(); // showAlertDialogButtonClicked(e.toString()); } //changing patient to patient_new object if (patient_new.getMiddle_name() == null) { patientName = patient_new.getFirst_name() + " " + patient_new.getLast_name(); } else { patientName = patient_new.getFirst_name() + " " + patient_new.getMiddle_name() + " " + patient_new.getLast_name(); } // setTitle(patientName); patinetName.setText(patientName); try { profileImage = imagesDAO.getPatientProfileChangeTime(patientUuid); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } if (patient_new.getPatient_photo() == null || patient_new.getPatient_photo().equalsIgnoreCase("")) { if (NetworkConnection.isOnline(getApplication())) { profilePicDownloaded(); } } if (!profileImage.equalsIgnoreCase(profileImage1)) { if (NetworkConnection.isOnline(getApplication())) { profilePicDownloaded(); } } Glide.with(PatientDetailActivity.this) .load(patient_new.getPatient_photo()) .thumbnail(0.3f) .centerCrop() .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .into(photoView); if (patient_new.getOpenmrs_id() != null && !patient_new.getOpenmrs_id().isEmpty()) { idView.setText(patient_new.getOpenmrs_id()); // sessionManager.setOfllineOpenMRSID(patient_new.getOpenmrs_id()); } else { idView.setText(getString(R.string.patient_not_registered)); } // if (!NetworkConnection.isOnline(getApplication())) { // if (!sessionManager.getOfllineOpenMRSID().equals("")) { // idView.setText(sessionManager.getOfllineOpenMRSID()); // } else { // idView.setText(getString(R.string.patient_not_registered)); // } // } setTitle(patient_new.getOpenmrs_id()); //String id = idView.toString(); //Log.d("IDEA","IDEA"+id); String age = DateAndTimeUtils.getAgeInYearMonth(patient_new.getDate_of_birth(), context); ageView.setText(age); String dob = DateAndTimeUtils.getFormatedDateOfBirthAsView(patient_new.getDate_of_birth()); dobView.setText(dob); if (patient_new.getAddress1() == null || patient_new.getAddress1().equals("")) { addr1View.setVisibility(View.GONE); } else { addr1View.setText(patient_new.getAddress1()); } if (patient_new.getAddress2() == null || patient_new.getAddress2().equals("")) { addr2Row.setVisibility(View.GONE); } else { addr2View.setText(patient_new.getAddress2()); } String city_village; if (patient_new.getCity_village() != null) { city_village = patient_new.getCity_village().trim(); } else { city_village = ""; } String postal_code; if (patient_new.getPostal_code() != null) { postal_code = patient_new.getPostal_code().trim() + ","; } else { postal_code = ""; } String addrFinalLine = String.format("%s, %s, %s %s", city_village, patient_new.getState_province(), postal_code, patient_new.getCountry()); addrFinalView.setText(addrFinalLine); phoneView.setText(patient_new.getPhone_number()); education_statusView.setText(patient_new.getEducation_level()); economic_statusView.setText(patient_new.getEconomic_status()); casteView.setText(patient_new.getCaste()); // if (patient_new.getSdw() != null && !patient_new.getSdw().equals("")) { sdwView.setText(patient_new.getSdw()); } else { sdwRow.setVisibility(View.GONE); } // if (patient_new.getOccupation() != null && !patient_new.getOccupation().equals("")) { occuView.setText(patient_new.getOccupation()); } else { occuRow.setVisibility(View.GONE); } if (visitUuid != null && !visitUuid.isEmpty()) { CardView histCardView = findViewById(R.id.cardView_history); histCardView.setVisibility(View.GONE); } else { visitUuidList = new ArrayList<>(); String visitIDSelection = "patientuuid = ?"; String[] visitIDArgs = {patientUuid}; Cursor visitIDCursor = db.query("tbl_visit", null, visitIDSelection, visitIDArgs, null, null, null); if (visitIDCursor != null && visitIDCursor.moveToFirst()) { do { visitUuid = visitIDCursor.getString(visitIDCursor.getColumnIndexOrThrow("uuid")); visitUuidList.add(visitUuid); } while (visitIDCursor.moveToNext()); } if (visitIDCursor != null) { visitIDCursor.close(); } for (String visituuid : visitUuidList) { Logger.logD(TAG, visituuid); EncounterDAO encounterDAO = new EncounterDAO(); String encounterIDSelection = "visituuid = ?"; String[] encounterIDArgs = {visituuid}; Cursor encounterCursor = db.query("tbl_encounter", null, encounterIDSelection, encounterIDArgs, null, null, null); if (encounterCursor != null && encounterCursor.moveToFirst()) { do { if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_VITALS").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encounterVitals = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_ADULTINITIAL").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encounterAdultIntials = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } } while (encounterCursor.moveToNext()); } encounterCursor.close(); } familyHistory(famHistView, patientUuid); pastMedicalHistory(medHistView, patientUuid); pastVisits(patientUuid); } } public void profilePicDownloaded() { UrlModifiers urlModifiers = new UrlModifiers(); String url = urlModifiers.patientProfileImageUrl(patientUuid); Logger.logD(TAG, "profileimage url" + url); Observable<ResponseBody> profilePicDownload = AppConstants.apiInterface.PERSON_PROFILE_PIC_DOWNLOAD(url, "Basic " + sessionManager.getEncoded()); profilePicDownload.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new DisposableObserver<ResponseBody>() { @Override public void onNext(ResponseBody file) { DownloadFilesUtils downloadFilesUtils = new DownloadFilesUtils(); downloadFilesUtils.saveToDisk(file, patientUuid); Logger.logD(TAG, file.toString()); } @Override public void onError(Throwable e) { Logger.logD(TAG, e.getMessage()); } @Override public void onComplete() { Logger.logD(TAG, "complete" + patient_new.getPatient_photo()); PatientsDAO patientsDAO = new PatientsDAO(); boolean updated = false; try { updated = patientsDAO.updatePatientPhoto(patientUuid, AppConstants.IMAGE_PATH + patientUuid + ".jpg"); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } if (updated) { Glide.with(PatientDetailActivity.this) .load(AppConstants.IMAGE_PATH + patientUuid + ".jpg") .thumbnail(0.3f) .centerCrop() .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .into(photoView); } ImagesDAO imagesDAO = new ImagesDAO(); boolean isImageDownloaded = false; try { isImageDownloaded = imagesDAO.insertPatientProfileImages(AppConstants.IMAGE_PATH + patientUuid + ".jpg", patientUuid); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } // if (isImageDownloaded) // AppConstants.notificationUtils.DownloadDone(getString(R.string.patient_image_download_notifi), "" + patient_new.getFirst_name() + "" + patient_new.getLast_name() + "'s Image Download Incomplete.", 4, getApplication()); // else // AppConstants.notificationUtils.DownloadDone(getString(R.string.patient_image_download_notifi), "" + patient_new.getFirst_name() + "" + patient_new.getLast_name() + "'s Image Download Incomplete.", 4, getApplication()); } }); } /** * This method retrieves details about patient's old visits. * * @param datetime variable of type String. * @return void */ private void createOldVisit(final String datetime, String visit_id, String end_datetime, String visitValue, String encounterVitalslocal, String encounterAdultIntialslocal) throws ParseException { final Boolean past_visit; final TextView textView = new TextView(this); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); final String visitString = String.format("Seen on (%s)", DateAndTimeUtils.SimpleDatetoLongDate(datetime)); if (end_datetime == null || end_datetime.isEmpty()) { // visit has not yet ended for (int i = 1; i <= 2; i++) { if (i == 1) { SpannableString spannableString = new SpannableString(visitString + " Active"); Object greenSpan = new BackgroundColorSpan(Color.GREEN); Object underlineSpan = new UnderlineSpan(); spannableString.setSpan(greenSpan, spannableString.length() - 6, spannableString.length(), 0); spannableString.setSpan(underlineSpan, 0, spannableString.length() - 7, 0); textView.setText(spannableString); layoutParams.setMargins(5, 10, 5, 0); // textView.setLayoutParams(layoutParams); textView.setTextSize(16); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); textView.setTypeface(typeface); previousVisitsList.addView(textView); } //If patient come up with any complaints if (i == 2) { TextView complaintxt1 = new TextView(this); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); complaintxt1.setTypeface(typeface); complaintxt1.setLayoutParams(layoutParams); if (visitValue != null && !visitValue.equals("")) { String visitComplaint = Html.fromHtml(visitValue).toString(); complaintxt1.setText(visitComplaint.replace(Node.bullet_arrow + "Associated symptoms", "")); } else { Log.e("Check", "No complaint"); } layoutParams.setMargins(5, 10, 5, 0); //complaintxt1.setLayoutParams(layoutParams); complaintxt1.setTextSize(16); previousVisitsList.addView(complaintxt1); } } past_visit = false; if (newVisit.isEnabled()) { newVisit.setEnabled(false); } if (newVisit.isClickable()) { newVisit.setClickable(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { newVisit.setBackgroundColor (getColor(R.color.divider)); newVisit.setTextColor(getColor(R.color.white)); } else { newVisit.setBackgroundColor(getResources().getColor(R.color.divider)); newVisit.setTextColor(getResources().getColor(R.color.white)); } } } else { // when visit has ended past_visit = true; for (int i = 1; i <= 2; i++) { if (i == 1) { textView.setText(visitString); textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); textView.setTypeface(typeface); textView.setTextSize(16); layoutParams.setMargins(5, 10, 5, 0); // textView.setLayoutParams(layoutParams); previousVisitsList.addView(textView); } //If patient has any past complaints if (i == 2) { TextView complaintxt1 = new TextView(this); if (visitValue != null && !visitValue.equals("")) { String visitComplaint = Html.fromHtml(visitValue).toString(); complaintxt1.setText(visitComplaint.replace(Node.bullet_arrow + "Associated symptoms", "")); } else { Log.e("Check", "No complaint"); } layoutParams.setMargins(5, 10, 5, 0); // complaintxt1.setLayoutParams(layoutParams); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); complaintxt1.setTypeface(typeface); complaintxt1.setTextSize(16); previousVisitsList.addView(complaintxt1); } } } textView.setTextSize(16); LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); llp.setMargins(0, 10, 0, 0); // textView.setLayoutParams(llp); textView.setTag(visit_id); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); textView.setTypeface(typeface); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // int position = (Integer) v.getTag(); Intent visitSummary = new Intent(PatientDetailActivity.this, VisitSummaryActivity.class); visitSummary.putExtra("visitUuid", visit_id); visitSummary.putExtra("patientUuid", patientUuid); visitSummary.putExtra("encounterUuidVitals", encounterVitalslocal); visitSummary.putExtra("encounterUuidAdultIntial", encounterAdultIntialslocal); visitSummary.putExtra("name", patientName); visitSummary.putExtra("tag", intentTag); visitSummary.putExtra("pastVisit", past_visit); if (hasPrescription.equalsIgnoreCase("true")) { visitSummary.putExtra("hasPrescription", "true"); } else { visitSummary.putExtra("hasPrescription", "false"); } startActivity(visitSummary); } }); //previousVisitsList.addView(textView); //TODO: add on click listener to open the previous visit } /** * This method is called when patient has no prior visits. * * @return void */ private void neverSeen() { final LayoutInflater inflater = PatientDetailActivity.this.getLayoutInflater(); View convertView = inflater.inflate(R.layout.list_item_previous_visit, null); TextView textView = convertView.findViewById(R.id.textView_visit_info); String visitString = getString(R.string.no_prior_visits); textView.setText(visitString); Typeface typeface = ResourcesCompat.getFont(this, R.font.lato_regular); textView.setTypeface(typeface); textView.setTextSize(16); previousVisitsList.addView(convertView); } @Override public void onBackPressed() { Intent i = new Intent(this, HomeActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); } public class Myreceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { idView.setText(patientsDAO.getOpenmrsId(patientUuid)); } catch (DAOException e) { Crashlytics.getInstance().core.logException(e); } setTitle(idView.getText()); } } public void familyHistory(TextView famHistView, String patientuuid) { String visitSelection = "patientuuid = ? AND enddate IS NULL OR enddate = ''"; String[] visitArgs = {patientuuid}; String[] visitColumns = {"uuid, startdate", "enddate"}; String visitOrderBy = "startdate"; Cursor visitCursor = db.query("tbl_visit", visitColumns, visitSelection, visitArgs, null, null, visitOrderBy); previousVisitsList = findViewById(R.id.linearLayout_previous_visits); if (visitCursor.getCount() < 1) { // neverSeen(); } else { if (visitCursor.moveToLast() && visitCursor != null) { do { EncounterDAO encounterDAO = new EncounterDAO(); String date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("startdate")); String end_date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("enddate")); String visit_id = visitCursor.getString(visitCursor.getColumnIndexOrThrow("uuid")); String encounterlocalAdultintial = ""; String encountervitalsLocal = null; String encounterIDSelection = "visituuid = ?"; String[] encounterIDArgs = {visit_id}; Cursor encounterCursor = db.query("tbl_encounter", null, encounterIDSelection, encounterIDArgs, null, null, null); if (encounterCursor != null && encounterCursor.moveToFirst()) { do { if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_VITALS").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encountervitalsLocal = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_ADULTINITIAL").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encounterlocalAdultintial = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } } while (encounterCursor.moveToNext()); } if (encounterCursor != null) { encounterCursor.close(); } String famHistSelection = "encounteruuid = ? AND conceptuuid = ? And voided!='1'"; String[] famHistArgs = {encounterlocalAdultintial, UuidDictionary.RHK_FAMILY_HISTORY_BLURB}; String[] famHistColumns = {"value", " conceptuuid"}; Cursor famHistCursor = db.query("tbl_obs", famHistColumns, famHistSelection, famHistArgs, null, null, null); famHistCursor.moveToLast(); String famHistValue; try { famHistValue = famHistCursor.getString(famHistCursor.getColumnIndexOrThrow("value")); } catch (Exception e) { famHistValue = ""; } finally { famHistCursor.close(); } if (famHistValue != null && !famHistValue.equals("")) { famHistView.setText(Html.fromHtml(famHistValue)); } else { famHistView.setText(getString(R.string.string_no_hist)); } } while (visitCursor.moveToPrevious()); } visitCursor.close(); } } public void pastMedicalHistory(TextView medHistView, String patientuuid) { String visitSelection = "patientuuid = ? AND enddate IS NULL OR enddate = ''"; String[] visitArgs = {patientuuid}; String[] visitColumns = {"uuid, startdate", "enddate"}; String visitOrderBy = "startdate"; Cursor visitCursor = db.query("tbl_visit", visitColumns, visitSelection, visitArgs, null, null, visitOrderBy); previousVisitsList = findViewById(R.id.linearLayout_previous_visits); if (visitCursor.getCount() < 1) { // neverSeen(); } else { if (visitCursor.moveToLast() && visitCursor != null) { do { EncounterDAO encounterDAO = new EncounterDAO(); String date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("startdate")); String end_date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("enddate")); String visit_id = visitCursor.getString(visitCursor.getColumnIndexOrThrow("uuid")); String encounterlocalAdultintial = ""; String encountervitalsLocal = null; String encounterIDSelection = "visituuid = ?"; String[] encounterIDArgs = {visit_id}; Cursor encounterCursor = db.query("tbl_encounter", null, encounterIDSelection, encounterIDArgs, null, null, null); if (encounterCursor != null && encounterCursor.moveToFirst()) { do { if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_VITALS").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encountervitalsLocal = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_ADULTINITIAL").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encounterlocalAdultintial = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } } while (encounterCursor.moveToNext()); } if (encounterCursor != null) { encounterCursor.close(); } String medHistSelection = "encounteruuid = ? AND conceptuuid = ? And voided!='1'"; String[] medHistArgs = {encounterlocalAdultintial, UuidDictionary.RHK_MEDICAL_HISTORY_BLURB}; String[] medHistColumms = {"value", " conceptuuid"}; Cursor medHistCursor = db.query("tbl_obs", medHistColumms, medHistSelection, medHistArgs, null, null, null); medHistCursor.moveToLast(); String medHistValue; try { medHistValue = medHistCursor.getString(medHistCursor.getColumnIndexOrThrow("value")); } catch (Exception e) { medHistValue = ""; } finally { medHistCursor.close(); } if (medHistValue != null && !medHistValue.equals("")) { medHistView.setText(Html.fromHtml(medHistValue)); } else { medHistView.setText(getString(R.string.string_no_hist)); } } while (visitCursor.moveToPrevious()); } visitCursor.close(); } } public void pastVisits(String patientuuid) { String visitSelection = "patientuuid = ?"; String[] visitArgs = {patientuuid}; String[] visitColumns = {"uuid, startdate", "enddate"}; String visitOrderBy = "startdate"; Cursor visitCursor = db.query("tbl_visit", visitColumns, visitSelection, visitArgs, null, null, visitOrderBy); previousVisitsList = findViewById(R.id.linearLayout_previous_visits); if (visitCursor.getCount() < 1) { neverSeen(); } else { if (visitCursor.moveToLast() && visitCursor != null) { do { EncounterDAO encounterDAO = new EncounterDAO(); String date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("startdate")); String end_date = visitCursor.getString(visitCursor.getColumnIndexOrThrow("enddate")); String visit_id = visitCursor.getString(visitCursor.getColumnIndexOrThrow("uuid")); String encounterlocalAdultintial = ""; String encountervitalsLocal = null; String encounterIDSelection = "visituuid = ?"; String[] encounterIDArgs = {visit_id}; Cursor encounterCursor = db.query("tbl_encounter", null, encounterIDSelection, encounterIDArgs, null, null, null); if (encounterCursor != null && encounterCursor.moveToFirst()) { do { if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_VITALS").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encountervitalsLocal = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } if (encounterDAO.getEncounterTypeUuid("ENCOUNTER_ADULTINITIAL").equalsIgnoreCase(encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("encounter_type_uuid")))) { encounterlocalAdultintial = encounterCursor.getString(encounterCursor.getColumnIndexOrThrow("uuid")); } } while (encounterCursor.moveToNext()); } encounterCursor.close(); String previsitSelection = "encounteruuid = ? AND conceptuuid = ? and voided !='1'"; String[] previsitArgs = {encounterlocalAdultintial, UuidDictionary.CURRENT_COMPLAINT}; String[] previsitColumms = {"value", " conceptuuid", "encounteruuid"}; Cursor previsitCursor = db.query("tbl_obs", previsitColumms, previsitSelection, previsitArgs, null, null, null); if (previsitCursor.moveToLast() && previsitCursor != null) { String visitValue = previsitCursor.getString(previsitCursor.getColumnIndexOrThrow("value")); if (visitValue != null && !visitValue.isEmpty()) { visitValue = visitValue.replace("?<b>",Node.bullet_arrow); String[] complaints = StringUtils.split(visitValue, Node.bullet_arrow); visitValue = ""; String colon = ":"; if (complaints != null) { for (String comp : complaints) { if (!comp.trim().isEmpty()) { visitValue = visitValue + Node.bullet_arrow + comp.substring(0, comp.indexOf(colon)) /*+ "<br/>"*/; } } if (!visitValue.isEmpty()) { visitValue = visitValue.substring(0, visitValue.length() - 2); visitValue = visitValue.replaceAll("<b>", ""); visitValue = visitValue.replaceAll("</b>", ""); } SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); try { Date formatted = currentDate.parse(date); String visitDate = currentDate.format(formatted); createOldVisit(visitDate, visit_id, end_date, visitValue, encountervitalsLocal, encounterlocalAdultintial); } catch (ParseException e) { Crashlytics.getInstance().core.logException(e); } } } // Called when we select complaints but not select any sub knowledgeEngine inside that complaint else { SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); try { Date formatted = currentDate.parse(date); String visitDate = currentDate.format(formatted); createOldVisit(visitDate, visit_id, end_date, visitValue, encountervitalsLocal, encounterlocalAdultintial); } catch (ParseException e) { Crashlytics.getInstance().core.logException(e); } } } // Called when we close app on vitals screen and Didn't select any complaints else { SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); try { Date formatted = currentDate.parse(date); String visitDate = currentDate.format(formatted); createOldVisit(visitDate, visit_id, end_date, visitValue, encountervitalsLocal, encounterlocalAdultintial); } catch (ParseException e) { Crashlytics.getInstance().core.logException(e); } } } while (visitCursor.moveToPrevious()); } } visitCursor.close(); } @Override protected void onStop() { super.onStop(); } public boolean onCreateOptionsMenu(Menu menu) { // Inflate the options menu from XML MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.detail_home: Intent intent = new Intent(PatientDetailActivity.this, HomeActivity.class); //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } }
new line issue of patientdetail screen.
app/src/main/java/app/intelehealth/client/activities/patientDetailActivity/PatientDetailActivity.java
new line issue of patientdetail screen.
Java
agpl-3.0
e9bc53b19f422fc7498c5384c3d9ead6cd91b433
0
ua-eas/kfs-devops-automation-fork,kuali/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,kuali/kfs,smith750/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,kuali/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,smith750/kfs,kuali/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,ua-eas/kfs,ua-eas/kfs,bhutchinson/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,smith750/kfs,bhutchinson/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,kuali/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,ua-eas/kfs,smith750/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,quikkian-ua-devops/kfs
/* * Copyright 2005-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.module.financial.document; import static org.kuali.kfs.KFSConstants.EMPTY_STRING; import static org.kuali.kfs.KFSConstants.GL_CREDIT_CODE; import static org.kuali.kfs.KFSConstants.GL_DEBIT_CODE; import static org.kuali.kfs.KFSPropertyConstants.BALANCE_TYPE; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.StringUtils; import org.kuali.core.document.AmountTotaling; import org.kuali.core.document.Copyable; import org.kuali.core.document.Correctable; import org.kuali.core.util.KualiDecimal; import org.kuali.kfs.bo.AccountingLineBase; import org.kuali.kfs.bo.AccountingLineParser; import org.kuali.kfs.bo.SourceAccountingLine; import org.kuali.kfs.document.AccountingDocumentBase; import org.kuali.module.chart.bo.codes.BalanceTyp; import org.kuali.module.financial.bo.JournalVoucherAccountingLineParser; import org.kuali.module.gl.util.SufficientFundsItem; import edu.iu.uis.eden.exception.WorkflowException; /** * This is the business object that represents the JournalVoucherDocument in Kuali. This is a transactional document that will * eventually post transactions to the G/L. It integrates with workflow and contains a single group of accounting lines. The Journal * Voucher is unique in that we only make use of one accounting line list: the source accounting lines seeing as a JV only records * accounting lines as debits or credits. */ public class JournalVoucherDocument extends AccountingDocumentBase implements VoucherDocument, Copyable, Correctable, AmountTotaling { private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(JournalVoucherDocument.class); // document specific attributes private String balanceTypeCode; // balanceType key private BalanceTyp balanceType; private java.sql.Date reversalDate; /** * Constructs a JournalVoucherDocument instance. */ public JournalVoucherDocument() { super(); this.balanceType = new BalanceTyp(); } /** * * @see org.kuali.kfs.document.AccountingDocumentBase#checkSufficientFunds() */ @Override public List<SufficientFundsItem> checkSufficientFunds() { LOG.debug("checkSufficientFunds() started"); // This document does not do sufficient funds checking return new ArrayList<SufficientFundsItem>(); } /** * This method retrieves the balance typ associated with this document. * * @return BalanceTyp */ public BalanceTyp getBalanceType() { return balanceType; } /** * This method sets the balance type associated with this document. * * @param balanceType * @deprecated */ @Deprecated public void setBalanceType(BalanceTyp balanceType) { this.balanceType = balanceType; } /** * Gets the balanceTypeCode attribute. * * @return Returns the balanceTypeCode. */ public String getBalanceTypeCode() { return balanceTypeCode; } /** * Sets the balanceTypeCode attribute value. * * @param balanceTypeCode The balanceTypeCode to set. */ public void setBalanceTypeCode(String balanceTypeCode) { this.balanceTypeCode = balanceTypeCode; } /** * This method retrieves the reversal date associated with this document. * * @return java.sql.Date */ public java.sql.Date getReversalDate() { return reversalDate; } /** * This method sets the reversal date associated with this document. * * @param reversalDate */ public void setReversalDate(java.sql.Date reversalDate) { this.reversalDate = reversalDate; } /** * Overrides the base implementation to return an empty string. * * @return String */ @Override public String getSourceAccountingLinesSectionTitle() { return EMPTY_STRING; } /** * Overrides the base implementation to return an empty string. * * @return String */ @Override public String getTargetAccountingLinesSectionTitle() { return EMPTY_STRING; } /** * This method calculates the debit total for a JV document keying off of the debit/debit code, only summing the accounting * lines with a debitDebitCode that matched the debit constant, and returns the results. * * @return KualiDecimal */ public KualiDecimal getDebitTotal() { KualiDecimal debitTotal = new KualiDecimal(0); AccountingLineBase al = null; Iterator iter = sourceAccountingLines.iterator(); while (iter.hasNext()) { al = (AccountingLineBase) iter.next(); if (StringUtils.isNotBlank(al.getDebitCreditCode()) && al.getDebitCreditCode().equals(GL_DEBIT_CODE)) { debitTotal = debitTotal.add(al.getAmount()); } } return debitTotal; } /** * This method calculates the credit total for a JV document keying off of the debit/credit code, only summing the accounting * lines with a debitCreditCode that matched the debit constant, and returns the results. * * @return KualiDecimal */ public KualiDecimal getCreditTotal() { KualiDecimal creditTotal = new KualiDecimal(0); AccountingLineBase al = null; Iterator iter = sourceAccountingLines.iterator(); while (iter.hasNext()) { al = (AccountingLineBase) iter.next(); if (StringUtils.isNotBlank(al.getDebitCreditCode()) && al.getDebitCreditCode().equals(GL_CREDIT_CODE)) { creditTotal = creditTotal.add(al.getAmount()); } } return creditTotal; } /** * This method determines the "total" for the JV document. If the selected balance type is an offset generation, then the total * is calculated by subtracting the debit accounting lines from the credit accounting lines. Otherwise, the total is just the * sum of all accounting line amounts. * * @return KualiDecimal the total of the JV document. */ public KualiDecimal getTotalDollarAmount() { KualiDecimal total = new KualiDecimal(0); AccountingLineBase al = null; this.refreshReferenceObject("balanceType"); if (this.balanceType.isFinancialOffsetGenerationIndicator()) { if (getCreditTotal().isGreaterThan(getDebitTotal())){ total = getCreditTotal(); } else { total = getDebitTotal(); } } else { total = getDebitTotal(); } return total; } /** * Used to get the appropriate <code>{@link AccountingLineParser}</code> for the <code>Document</code> * * @return AccountingLineParser */ @Override public AccountingLineParser getAccountingLineParser() { return new JournalVoucherAccountingLineParser(getBalanceTypeCode()); } /** * @see org.kuali.kfs.document.AccountingDocumentBase#toErrorCorrection() */ @Override public void toErrorCorrection() throws WorkflowException { super.toErrorCorrection(); processJournalVoucherErrorCorrections(); } /** * This method checks to make sure that the JV that we are dealing with was one that was created in debit/credit mode, not * single amount entry mode. If this is a debit/credit JV, then iterate over each source line and flip the sign on the amount to * nullify the super's effect, then flip the debit/credit code b/c an error corrected JV flips the debit/credit code. */ private void processJournalVoucherErrorCorrections() { Iterator i = getSourceAccountingLines().iterator(); this.refreshReferenceObject(BALANCE_TYPE); if (this.getBalanceType().isFinancialOffsetGenerationIndicator()) { // make sure this is not a single amount entered JV int index = 0; while (i.hasNext()) { SourceAccountingLine sLine = (SourceAccountingLine) i.next(); String debitCreditCode = sLine.getDebitCreditCode(); if (StringUtils.isNotBlank(debitCreditCode)) { // negate the amount to to nullify the effects of the super, b/c super flipped it the first time through sLine.setAmount(sLine.getAmount().negated()); // offsets the effect the super // now just flip the debit/credit code if (GL_DEBIT_CODE.equals(debitCreditCode)) { sLine.setDebitCreditCode(GL_CREDIT_CODE); } else if (GL_CREDIT_CODE.equals(debitCreditCode)) { sLine.setDebitCreditCode(GL_DEBIT_CODE); } else { throw new IllegalStateException("SourceAccountingLine at index " + index + " does not have a debit/credit " + "code associated with it. This should never have occured. Please contact your system administrator."); } index++; } } } } }
work/src/org/kuali/kfs/fp/document/JournalVoucherDocument.java
/* * Copyright 2005-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.module.financial.document; import static org.kuali.kfs.KFSConstants.EMPTY_STRING; import static org.kuali.kfs.KFSConstants.GL_CREDIT_CODE; import static org.kuali.kfs.KFSConstants.GL_DEBIT_CODE; import static org.kuali.kfs.KFSPropertyConstants.BALANCE_TYPE; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.StringUtils; import org.kuali.core.document.AmountTotaling; import org.kuali.core.document.Copyable; import org.kuali.core.document.Correctable; import org.kuali.core.util.KualiDecimal; import org.kuali.kfs.bo.AccountingLineBase; import org.kuali.kfs.bo.AccountingLineParser; import org.kuali.kfs.bo.SourceAccountingLine; import org.kuali.kfs.document.AccountingDocumentBase; import org.kuali.module.chart.bo.codes.BalanceTyp; import org.kuali.module.financial.bo.JournalVoucherAccountingLineParser; import org.kuali.module.gl.util.SufficientFundsItem; import edu.iu.uis.eden.exception.WorkflowException; /** * This is the business object that represents the JournalVoucherDocument in Kuali. This is a transactional document that will * eventually post transactions to the G/L. It integrates with workflow and contains a single group of accounting lines. The Journal * Voucher is unique in that we only make use of one accounting line list: the source accounting lines seeing as a JV only records * accounting lines as debits or credits. */ public class JournalVoucherDocument extends AccountingDocumentBase implements VoucherDocument, Copyable, Correctable, AmountTotaling { private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(JournalVoucherDocument.class); // document specific attributes private String balanceTypeCode; // balanceType key private BalanceTyp balanceType; private java.sql.Date reversalDate; /** * Constructs a JournalVoucherDocument instance. */ public JournalVoucherDocument() { super(); this.balanceType = new BalanceTyp(); } /** * * @see org.kuali.kfs.document.AccountingDocumentBase#checkSufficientFunds() */ @Override public List<SufficientFundsItem> checkSufficientFunds() { LOG.debug("checkSufficientFunds() started"); // This document does not do sufficient funds checking return new ArrayList<SufficientFundsItem>(); } /** * This method retrieves the balance typ associated with this document. * * @return BalanceTyp */ public BalanceTyp getBalanceType() { return balanceType; } /** * This method sets the balance type associated with this document. * * @param balanceType * @deprecated */ @Deprecated public void setBalanceType(BalanceTyp balanceType) { this.balanceType = balanceType; } /** * Gets the balanceTypeCode attribute. * * @return Returns the balanceTypeCode. */ public String getBalanceTypeCode() { return balanceTypeCode; } /** * Sets the balanceTypeCode attribute value. * * @param balanceTypeCode The balanceTypeCode to set. */ public void setBalanceTypeCode(String balanceTypeCode) { this.balanceTypeCode = balanceTypeCode; } /** * This method retrieves the reversal date associated with this document. * * @return java.sql.Date */ public java.sql.Date getReversalDate() { return reversalDate; } /** * This method sets the reversal date associated with this document. * * @param reversalDate */ public void setReversalDate(java.sql.Date reversalDate) { this.reversalDate = reversalDate; } /** * Overrides the base implementation to return an empty string. * * @return String */ @Override public String getSourceAccountingLinesSectionTitle() { return EMPTY_STRING; } /** * Overrides the base implementation to return an empty string. * * @return String */ @Override public String getTargetAccountingLinesSectionTitle() { return EMPTY_STRING; } /** * This method calculates the debit total for a JV document keying off of the debit/debit code, only summing the accounting * lines with a debitDebitCode that matched the debit constant, and returns the results. * * @return KualiDecimal */ public KualiDecimal getDebitTotal() { KualiDecimal debitTotal = new KualiDecimal(0); AccountingLineBase al = null; Iterator iter = sourceAccountingLines.iterator(); while (iter.hasNext()) { al = (AccountingLineBase) iter.next(); if (StringUtils.isNotBlank(al.getDebitCreditCode()) && al.getDebitCreditCode().equals(GL_DEBIT_CODE)) { debitTotal = debitTotal.add(al.getAmount()); } } return debitTotal; } /** * This method calculates the credit total for a JV document keying off of the debit/credit code, only summing the accounting * lines with a debitCreditCode that matched the debit constant, and returns the results. * * @return KualiDecimal */ public KualiDecimal getCreditTotal() { KualiDecimal creditTotal = new KualiDecimal(0); AccountingLineBase al = null; Iterator iter = sourceAccountingLines.iterator(); while (iter.hasNext()) { al = (AccountingLineBase) iter.next(); if (StringUtils.isNotBlank(al.getDebitCreditCode()) && al.getDebitCreditCode().equals(GL_CREDIT_CODE)) { creditTotal = creditTotal.add(al.getAmount()); } } return creditTotal; } /** * This method determines the "total" for the JV document. If the selected balance type is an offset generation, then the total * is calculated by subtracting the debit accounting lines from the credit accounting lines. Otherwise, the total is just the * sum of all accounting line amounts. * * @return KualiDecimal the total of the JV document. */ public KualiDecimal getTotalDollarAmount() { KualiDecimal total = new KualiDecimal(0); AccountingLineBase al = null; this.refreshReferenceObject("balanceType"); if (this.balanceType.isFinancialOffsetGenerationIndicator()) { // credits and debits mode total = getCreditTotal().subtract(getDebitTotal()); } else { // single amount mode Iterator iter = sourceAccountingLines.iterator(); while (iter.hasNext()) { al = (AccountingLineBase) iter.next(); total = total.add(al.getAmount()); } } return total; } /** * Used to get the appropriate <code>{@link AccountingLineParser}</code> for the <code>Document</code> * * @return AccountingLineParser */ @Override public AccountingLineParser getAccountingLineParser() { return new JournalVoucherAccountingLineParser(getBalanceTypeCode()); } /** * @see org.kuali.kfs.document.AccountingDocumentBase#toErrorCorrection() */ @Override public void toErrorCorrection() throws WorkflowException { super.toErrorCorrection(); processJournalVoucherErrorCorrections(); } /** * This method checks to make sure that the JV that we are dealing with was one that was created in debit/credit mode, not * single amount entry mode. If this is a debit/credit JV, then iterate over each source line and flip the sign on the amount to * nullify the super's effect, then flip the debit/credit code b/c an error corrected JV flips the debit/credit code. */ private void processJournalVoucherErrorCorrections() { Iterator i = getSourceAccountingLines().iterator(); this.refreshReferenceObject(BALANCE_TYPE); if (this.getBalanceType().isFinancialOffsetGenerationIndicator()) { // make sure this is not a single amount entered JV int index = 0; while (i.hasNext()) { SourceAccountingLine sLine = (SourceAccountingLine) i.next(); String debitCreditCode = sLine.getDebitCreditCode(); if (StringUtils.isNotBlank(debitCreditCode)) { // negate the amount to to nullify the effects of the super, b/c super flipped it the first time through sLine.setAmount(sLine.getAmount().negated()); // offsets the effect the super // now just flip the debit/credit code if (GL_DEBIT_CODE.equals(debitCreditCode)) { sLine.setDebitCreditCode(GL_CREDIT_CODE); } else if (GL_CREDIT_CODE.equals(debitCreditCode)) { sLine.setDebitCreditCode(GL_DEBIT_CODE); } else { throw new IllegalStateException("SourceAccountingLine at index " + index + " does not have a debit/credit " + "code associated with it. This should never have occured. Please contact your system administrator."); } index++; } } } } }
KULRNE-4946: Revisted total amount calculation per new functional specification.
work/src/org/kuali/kfs/fp/document/JournalVoucherDocument.java
KULRNE-4946: Revisted total amount calculation per new functional specification.
Java
lgpl-2.1
ad026eba68b2d789a23dd102d59afb000e2244f7
0
rhusar/wildfly,rhusar/wildfly,pferraro/wildfly,iweiss/wildfly,tomazzupan/wildfly,99sono/wildfly,wildfly/wildfly,iweiss/wildfly,tadamski/wildfly,tomazzupan/wildfly,jstourac/wildfly,jstourac/wildfly,pferraro/wildfly,golovnin/wildfly,xasx/wildfly,wildfly/wildfly,golovnin/wildfly,xasx/wildfly,tomazzupan/wildfly,pferraro/wildfly,rhusar/wildfly,99sono/wildfly,tadamski/wildfly,wildfly/wildfly,pferraro/wildfly,wildfly/wildfly,golovnin/wildfly,iweiss/wildfly,99sono/wildfly,tadamski/wildfly,rhusar/wildfly,xasx/wildfly,jstourac/wildfly,iweiss/wildfly,jstourac/wildfly
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.connector.subsystems.datasources; import java.sql.Driver; import java.util.List; import org.jboss.as.connector.ConnectorServices; import org.jboss.as.connector.registry.DriverRegistry; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.ServiceVerificationHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.naming.service.NamingService; import org.jboss.as.security.service.SubjectFactoryService; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.jca.core.api.connectionmanager.ccm.CachedConnectionManager; import org.jboss.jca.core.api.management.ManagementRepository; import org.jboss.jca.core.spi.transaction.TransactionIntegration; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; import org.jboss.security.SubjectFactory; import static org.jboss.as.connector.ConnectorMessages.MESSAGES; import static org.jboss.as.connector.subsystems.datasources.Constants.DATASOURCE_DRIVER; import static org.jboss.as.connector.subsystems.datasources.Constants.JNDINAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; /** * Abstract operation handler responsible for adding a DataSource. * * @author John Bailey */ public abstract class AbstractDataSourceAdd extends AbstractAddStepHandler { protected void performRuntime(final OperationContext context, ModelNode operation, ModelNode model, final ServiceVerificationHandler verificationHandler, final List<ServiceController<?>> controllers) throws OperationFailedException { final ModelNode address = operation.require(OP_ADDR); final String dsName = PathAddress.pathAddress(address).getLastElement().getValue(); final String jndiName = model.get(JNDINAME.getName()).asString(); final ServiceTarget serviceTarget = context.getServiceTarget(); boolean enabled = false; //!operation.hasDefined(ENABLED.getName()) || operation.get(ENABLED.getName()).asBoolean(); ModelNode node = DATASOURCE_DRIVER.resolveModelAttribute(context, model); AbstractDataSourceService dataSourceService = createDataSourceService(dsName); final ManagementResourceRegistration registration = context.getResourceRegistrationForUpdate(); final ServiceName dataSourceServiceName = AbstractDataSourceService.SERVICE_NAME_BASE.append(jndiName); final ServiceBuilder<?> dataSourceServiceBuilder = serviceTarget .addService(dataSourceServiceName, dataSourceService) .addDependency(ConnectorServices.TRANSACTION_INTEGRATION_SERVICE, TransactionIntegration.class, dataSourceService.getTransactionIntegrationInjector()) .addDependency(ConnectorServices.MANAGEMENT_REPOSITORY_SERVICE, ManagementRepository.class, dataSourceService.getManagementRepositoryInjector()) .addDependency(SubjectFactoryService.SERVICE_NAME, SubjectFactory.class, dataSourceService.getSubjectFactoryInjector()) .addDependency(ConnectorServices.JDBC_DRIVER_REGISTRY_SERVICE, DriverRegistry.class, dataSourceService.getDriverRegistryInjector()) .addDependency(ConnectorServices.CCM_SERVICE, CachedConnectionManager.class, dataSourceService.getCcmInjector()) .addDependency(ConnectorServices.IDLE_REMOVER_SERVICE) .addDependency(ConnectorServices.CONNECTION_VALIDATOR_SERVICE) .addDependency(NamingService.SERVICE_NAME); dataSourceServiceBuilder.addListener(new DataSourceStatisticsListener(registration, dsName)); startConfigAndAddDependency(dataSourceServiceBuilder, dataSourceService, dsName, serviceTarget, operation, verificationHandler); final String driverName = node.asString(); final ServiceName driverServiceName = ServiceName.JBOSS.append("jdbc-driver", driverName.replaceAll("\\.", "_")); if (!context.isBooting()) { final ServiceRegistry registry = context.getServiceRegistry(true); final ServiceController<?> dataSourceController = registry.getService(driverServiceName); if (driverServiceName != null && dataSourceController != null) { dataSourceServiceBuilder.addDependency(driverServiceName, Driver.class, dataSourceService.getDriverInjector()); } else { throw new OperationFailedException(MESSAGES.driverNotPresent(driverName)); } } else { dataSourceServiceBuilder.addDependency(driverServiceName, Driver.class, dataSourceService.getDriverInjector()); } dataSourceServiceBuilder.setInitialMode(ServiceController.Mode.NEVER); controllers.add(dataSourceServiceBuilder.install()); } static String cleanupJavaContext(String jndiName) { String bindName; if (jndiName.startsWith("java:/")) { bindName = jndiName.substring(6); } else if(jndiName.startsWith("java:")) { bindName = jndiName.substring(5); } else { bindName = jndiName; } return bindName; } protected abstract void startConfigAndAddDependency(ServiceBuilder<?> dataSourceServiceBuilder, AbstractDataSourceService dataSourceService, String jndiName, ServiceTarget serviceTarget, final ModelNode operation, final ServiceVerificationHandler serviceVerificationHandler) throws OperationFailedException; protected abstract void populateModel(final ModelNode operation, final ModelNode model) throws OperationFailedException; protected abstract AbstractDataSourceService createDataSourceService(final String jndiName) throws OperationFailedException; static void populateAddModel(final ModelNode operation, final ModelNode modelNode, final String connectionPropertiesProp, final SimpleAttributeDefinition[] attributes) throws OperationFailedException { if (operation.hasDefined(connectionPropertiesProp)) { for (Property property : operation.get(connectionPropertiesProp).asPropertyList()) { modelNode.get(connectionPropertiesProp, property.getName()).set(property.getValue().asString()); } } for (final SimpleAttributeDefinition attribute : attributes) { attribute.validateAndSet(operation, modelNode); } //modelNode.get(ENABLED.getName()).set(false); } }
connector/src/main/java/org/jboss/as/connector/subsystems/datasources/AbstractDataSourceAdd.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.connector.subsystems.datasources; import java.sql.Driver; import java.util.List; import org.jboss.as.connector.ConnectorServices; import org.jboss.as.connector.registry.DriverRegistry; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.ServiceVerificationHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.naming.service.NamingService; import org.jboss.as.security.service.SubjectFactoryService; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.jca.core.api.connectionmanager.ccm.CachedConnectionManager; import org.jboss.jca.core.api.management.ManagementRepository; import org.jboss.jca.core.spi.transaction.TransactionIntegration; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; import org.jboss.security.SubjectFactory; import static org.jboss.as.connector.ConnectorMessages.MESSAGES; import static org.jboss.as.connector.subsystems.datasources.Constants.DATASOURCE_DRIVER; import static org.jboss.as.connector.subsystems.datasources.Constants.JNDINAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; /** * Abstract operation handler responsible for adding a DataSource. * * @author John Bailey */ public abstract class AbstractDataSourceAdd extends AbstractAddStepHandler { protected void performRuntime(final OperationContext context, ModelNode operation, ModelNode model, final ServiceVerificationHandler verificationHandler, final List<ServiceController<?>> controllers) throws OperationFailedException { final ModelNode address = operation.require(OP_ADDR); final String dsName = PathAddress.pathAddress(address).getLastElement().getValue(); final String jndiName = model.get(JNDINAME.getName()).asString(); final ServiceTarget serviceTarget = context.getServiceTarget(); boolean enabled = false; //!operation.hasDefined(ENABLED.getName()) || operation.get(ENABLED.getName()).asBoolean(); ModelNode node = operation.require(DATASOURCE_DRIVER.getName()); AbstractDataSourceService dataSourceService = createDataSourceService(dsName); final ManagementResourceRegistration registration = context.getResourceRegistrationForUpdate(); final ServiceName dataSourceServiceName = AbstractDataSourceService.SERVICE_NAME_BASE.append(jndiName); final ServiceBuilder<?> dataSourceServiceBuilder = serviceTarget .addService(dataSourceServiceName, dataSourceService) .addDependency(ConnectorServices.TRANSACTION_INTEGRATION_SERVICE, TransactionIntegration.class, dataSourceService.getTransactionIntegrationInjector()) .addDependency(ConnectorServices.MANAGEMENT_REPOSITORY_SERVICE, ManagementRepository.class, dataSourceService.getManagementRepositoryInjector()) .addDependency(SubjectFactoryService.SERVICE_NAME, SubjectFactory.class, dataSourceService.getSubjectFactoryInjector()) .addDependency(ConnectorServices.JDBC_DRIVER_REGISTRY_SERVICE, DriverRegistry.class, dataSourceService.getDriverRegistryInjector()) .addDependency(ConnectorServices.CCM_SERVICE, CachedConnectionManager.class, dataSourceService.getCcmInjector()) .addDependency(ConnectorServices.IDLE_REMOVER_SERVICE) .addDependency(ConnectorServices.CONNECTION_VALIDATOR_SERVICE) .addDependency(NamingService.SERVICE_NAME); dataSourceServiceBuilder.addListener(new DataSourceStatisticsListener(registration, dsName)); startConfigAndAddDependency(dataSourceServiceBuilder, dataSourceService, dsName, serviceTarget, operation, verificationHandler); final String driverName = node.asString(); final ServiceName driverServiceName = ServiceName.JBOSS.append("jdbc-driver", driverName.replaceAll("\\.", "_")); if (!context.isBooting()) { final ServiceRegistry registry = context.getServiceRegistry(true); final ServiceController<?> dataSourceController = registry.getService(driverServiceName); if (driverServiceName != null && dataSourceController != null) { dataSourceServiceBuilder.addDependency(driverServiceName, Driver.class, dataSourceService.getDriverInjector()); } else { throw new OperationFailedException(MESSAGES.driverNotPresent(driverName)); } } else { dataSourceServiceBuilder.addDependency(driverServiceName, Driver.class, dataSourceService.getDriverInjector()); } dataSourceServiceBuilder.setInitialMode(ServiceController.Mode.NEVER); controllers.add(dataSourceServiceBuilder.install()); } static String cleanupJavaContext(String jndiName) { String bindName; if (jndiName.startsWith("java:/")) { bindName = jndiName.substring(6); } else if(jndiName.startsWith("java:")) { bindName = jndiName.substring(5); } else { bindName = jndiName; } return bindName; } protected abstract void startConfigAndAddDependency(ServiceBuilder<?> dataSourceServiceBuilder, AbstractDataSourceService dataSourceService, String jndiName, ServiceTarget serviceTarget, final ModelNode operation, final ServiceVerificationHandler serviceVerificationHandler) throws OperationFailedException; protected abstract void populateModel(final ModelNode operation, final ModelNode model) throws OperationFailedException; protected abstract AbstractDataSourceService createDataSourceService(final String jndiName) throws OperationFailedException; static void populateAddModel(final ModelNode operation, final ModelNode modelNode, final String connectionPropertiesProp, final SimpleAttributeDefinition[] attributes) throws OperationFailedException { if (operation.hasDefined(connectionPropertiesProp)) { for (Property property : operation.get(connectionPropertiesProp).asPropertyList()) { modelNode.get(connectionPropertiesProp, property.getName()).set(property.getValue().asString()); } } for (final SimpleAttributeDefinition attribute : attributes) { attribute.validateAndSet(operation, modelNode); } //modelNode.get(ENABLED.getName()).set(false); } }
AS7-4590 Resolve the driver-name expression
connector/src/main/java/org/jboss/as/connector/subsystems/datasources/AbstractDataSourceAdd.java
AS7-4590 Resolve the driver-name expression
Java
lgpl-2.1
95a13038cd021ab7c030b13bd262b791ff495868
0
xwiki/xwiki-commons,xwiki/xwiki-commons
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.job.internal; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Inject; import javax.inject.Singleton; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.component.phase.Initializable; import org.xwiki.component.phase.InitializationException; import org.xwiki.job.JobManagerConfiguration; import org.xwiki.job.event.status.JobStatus; import org.xwiki.job.internal.xstream.SafeArrayConverter; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.mapper.MapperWrapper; /** * Default implementation of {@link JobStatusStorage}. * * @version $Id$ * @since 4.0M1 */ @Component @Singleton public class DefaultJobStatusStorage implements JobStatusStorage, Initializable { /** * The name of the file where the job status is stored. */ private static final String FILENAME_STATUS = "status.xml"; /** * Encoding used for file content and names. */ private static final String DEFAULT_ENCODING = "UTF-8"; /** * The encoded version of a <code>null</code> value in the id list. */ private static final String FOLDER_NULL = "&null"; /** * The name of the folder containing a job status. */ private static final String FOLDER_STATUS = "&status"; /** * Used to get the storage directory. */ @Inject private JobManagerConfiguration configuration; /** * The logger to log. */ @Inject private Logger logger; /** * Used to serialize and unserialize status. */ private XStream xstream; /** * A cache of stored job statuses. */ private Map<List<String>, JobStatus> jobs = new ConcurrentHashMap<List<String>, JobStatus>(); @Override public void initialize() throws InitializationException { this.xstream = new XStream() { @Override protected MapperWrapper wrapMapper(MapperWrapper next) { return new MapperWrapper(next) { @Override public boolean shouldSerializeMember(Class definedIn, String fieldName) { // Make XStream a bit stronger (we don't care if some field is missing) return definedIn != Object.class ? super.shouldSerializeMember(definedIn, fieldName) : false; } }; } }; // Make unserialization of LogEvent as strong as possible this.xstream.registerConverter(new SafeArrayConverter(this.xstream.getMapper(), this.logger)); try { load(); } catch (Exception e) { this.logger.error("Failed to load jobs", e); } } /** * @param name the file or directory name to encode * @return the encoding name */ private String encode(String name) { String encoded; if (name != null) { try { encoded = URLEncoder.encode(name, DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // Should never happen encoded = name; } } else { encoded = FOLDER_NULL; } return encoded; } /** * Load jobs from directory. */ private void load() { File folder = this.configuration.getStorage(); if (folder.exists()) { loadFolder(folder); } } /** * @param folder the folder from where to load the jobs */ private void loadFolder(File folder) { for (File file : folder.listFiles()) { if (file.isDirectory()) { if (file.getName().equals(FOLDER_STATUS)) { loadStatus(file); } else { loadFolder(file); } } else if (file.getName().equals(FILENAME_STATUS)) { loadStatus(folder); } } } /** * @param folder the folder from where to load the job status */ private void loadStatus(File folder) { File statusFile = new File(folder, FILENAME_STATUS); if (statusFile.exists()) { try { JobStatus status = loadJobStatus(statusFile); List<String> id = status.getRequest().getId(); this.jobs.put(id != null ? id : Collections.<String> emptyList(), status); } catch (Exception e) { this.logger.error("Failed to load job status from file [{}]", statusFile, e); } } } /** * @param statusFile the file containing job status to load * @return the job status * @throws Exception when failing to load the job status from the file */ private JobStatus loadJobStatus(File statusFile) throws Exception { return (JobStatus) this.xstream.fromXML(statusFile); } // JobStatusStorage /** * @param id the id of the job * @return the folder where to store the job related informations */ private File getJobFolder(List<String> id) { File folder = this.configuration.getStorage(); for (String idElement : id) { folder = new File(folder, encode(idElement)); } return folder; } /** * @param status the job status to save * @throws IOException when falling to store the provided status */ private void saveJobStatus(JobStatus status) throws IOException { File statusFile = getJobFolder(status.getRequest().getId()); statusFile = new File(statusFile, FILENAME_STATUS); FileOutputStream stream = FileUtils.openOutputStream(statusFile); try { OutputStreamWriter writer = new OutputStreamWriter(stream, DEFAULT_ENCODING); writer.write("<?xml version=\"1.0\" encoding=\"" + DEFAULT_ENCODING + "\"?>\n"); this.xstream.toXML(status, writer); writer.flush(); } finally { IOUtils.closeQuietly(stream); } } @Override public JobStatus getJobStatus(String id) { return getJobStatus(id != null ? Arrays.asList(id) : (List<String>) null); } @Override public JobStatus getJobStatus(List<String> id) { return this.jobs.get(id != null ? id : Collections.EMPTY_LIST); } @Override public void store(JobStatus status) { this.jobs.put(status.getRequest().getId(), status); // On store Serializable job status on file system if (status instanceof Serializable) { try { saveJobStatus(status); } catch (Exception e) { this.logger.warn("Failed to save job status [{}]", status, e); } } } @Override public JobStatus remove(String id) { return remove(Arrays.asList(id)); } @Override public JobStatus remove(List<String> id) { JobStatus status = this.jobs.remove(id); File jobFolder = getJobFolder(id); if (jobFolder.exists()) { try { FileUtils.deleteDirectory(jobFolder); } catch (IOException e) { this.logger.warn("Failed to delete job folder [{}]", jobFolder, e); } } return status; } }
xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/internal/DefaultJobStatusStorage.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.job.internal; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Inject; import javax.inject.Singleton; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.component.phase.Initializable; import org.xwiki.component.phase.InitializationException; import org.xwiki.job.JobManagerConfiguration; import org.xwiki.job.event.status.JobStatus; import org.xwiki.job.internal.xstream.SafeArrayConverter; import com.thoughtworks.xstream.XStream; /** * Default implementation of {@link JobStatusStorage}. * * @version $Id$ * @since 4.0M1 */ @Component @Singleton public class DefaultJobStatusStorage implements JobStatusStorage, Initializable { /** * The name of the file where the job status is stored. */ private static final String FILENAME_STATUS = "status.xml"; /** * Encoding used for file content and names. */ private static final String DEFAULT_ENCODING = "UTF-8"; /** * The encoded version of a <code>null</code> value in the id list. */ private static final String FOLDER_NULL = "&null"; /** * The name of the folder containing a job status. */ private static final String FOLDER_STATUS = "&status"; /** * Used to get the storage directory. */ @Inject private JobManagerConfiguration configuration; /** * The logger to log. */ @Inject private Logger logger; /** * Used to serialize and unserialize status. */ private XStream xstream; /** * A cache of stored job statuses. */ private Map<List<String>, JobStatus> jobs = new ConcurrentHashMap<List<String>, JobStatus>(); @Override public void initialize() throws InitializationException { this.xstream = new XStream(); // Make unserialization of LogEvent as strong as possible this.xstream.registerConverter(new SafeArrayConverter(this.xstream.getMapper(), this.logger)); try { load(); } catch (Exception e) { this.logger.error("Failed to load jobs", e); } } /** * @param name the file or directory name to encode * @return the encoding name */ private String encode(String name) { String encoded; if (name != null) { try { encoded = URLEncoder.encode(name, DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // Should never happen encoded = name; } } else { encoded = FOLDER_NULL; } return encoded; } /** * Load jobs from directory. */ private void load() { File folder = this.configuration.getStorage(); if (folder.exists()) { loadFolder(folder); } } /** * @param folder the folder from where to load the jobs */ private void loadFolder(File folder) { for (File file : folder.listFiles()) { if (file.isDirectory()) { if (file.getName().equals(FOLDER_STATUS)) { loadStatus(file); } else { loadFolder(file); } } else if (file.getName().equals(FILENAME_STATUS)) { loadStatus(folder); } } } /** * @param folder the folder from where to load the job status */ private void loadStatus(File folder) { File statusFile = new File(folder, FILENAME_STATUS); if (statusFile.exists()) { try { JobStatus status = loadJobStatus(statusFile); List<String> id = status.getRequest().getId(); this.jobs.put(id != null ? id : Collections.<String> emptyList(), status); } catch (Exception e) { this.logger.error("Failed to load job status from file [{}]", statusFile, e); } } } /** * @param statusFile the file containing job status to load * @return the job status * @throws Exception when failing to load the job status from the file */ private JobStatus loadJobStatus(File statusFile) throws Exception { return (JobStatus) this.xstream.fromXML(statusFile); } // JobStatusStorage /** * @param id the id of the job * @return the folder where to store the job related informations */ private File getJobFolder(List<String> id) { File folder = this.configuration.getStorage(); for (String idElement : id) { folder = new File(folder, encode(idElement)); } return folder; } /** * @param status the job status to save * @throws IOException when falling to store the provided status */ private void saveJobStatus(JobStatus status) throws IOException { File statusFile = getJobFolder(status.getRequest().getId()); statusFile = new File(statusFile, FILENAME_STATUS); FileOutputStream stream = FileUtils.openOutputStream(statusFile); try { OutputStreamWriter writer = new OutputStreamWriter(stream, DEFAULT_ENCODING); writer.write("<?xml version=\"1.0\" encoding=\"" + DEFAULT_ENCODING + "\"?>\n"); this.xstream.toXML(status, writer); writer.flush(); } finally { IOUtils.closeQuietly(stream); } } @Override public JobStatus getJobStatus(String id) { return getJobStatus(id != null ? Arrays.asList(id) : (List<String>) null); } @Override public JobStatus getJobStatus(List<String> id) { return this.jobs.get(id != null ? id : Collections.EMPTY_LIST); } @Override public void store(JobStatus status) { this.jobs.put(status.getRequest().getId(), status); // On store Serializable job status on file system if (status instanceof Serializable) { try { saveJobStatus(status); } catch (Exception e) { this.logger.warn("Failed to save job status [{}]", status, e); } } } @Override public JobStatus remove(String id) { return remove(Arrays.asList(id)); } @Override public JobStatus remove(List<String> id) { JobStatus status = this.jobs.remove(id); File jobFolder = getJobFolder(id); if (jobFolder.exists()) { try { FileUtils.deleteDirectory(jobFolder); } catch (IOException e) { this.logger.warn("Failed to delete job folder [{}]", jobFolder, e); } } return status; } }
Bulletproofing
xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/internal/DefaultJobStatusStorage.java
Bulletproofing
Java
apache-2.0
4b2e74b84f3e44a4c2b473b717aa0128d4cc35b1
0
springbootbuch/extconfig,springbootbuch/extconfig
package de.springbootbuch.extconfig; import java.net.URL; import java.util.List; import java.util.Map; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties("example") public class ExampleProperties { public static class Server { /** The name of the server. */ private String name; /** The URL of the server. */ private URL url; public String getName() { return name; } public void setName(String name) { this.name = name; } public URL getUrl() { return url; } public void setUrl(URL url) { this.url = url; } @Override public String toString() { return "Server{" + "name=" + name + ", url=" + url + '}'; } } public static enum Environment { dev, prod, cloud } /** The greeting used. */ @NotNull @Size(min = 1) private String greeting; /** Some arbitrary interval. */ @Min(10) private Integer interval; /** An example of maps. */ private Map<Environment, Map<String, Object>> environments; /** The list of servers. */ private List<Server> servers; /** A precision. */ private Double precision; public String getGreeting() { return greeting; } public void setGreeting(String greeting) { this.greeting = greeting; } public Integer getInterval() { return interval; } public void setInterval(Integer interval) { this.interval = interval; } public Map<Environment, Map<String, Object>> getEnvironments() { return environments; } public void setEnvironments(Map<Environment, Map<String, Object>> environments) { this.environments = environments; } public List<Server> getServers() { return servers; } public void setServers(List<Server> servers) { this.servers = servers; } public Double getPrecision() { return precision; } public void setPrecision(Double precision) { this.precision = precision; } @Override public String toString() { final StringBuilder rv = new StringBuilder(); rv .append("ExampleProperties{") .append("\n\tgreeting=").append(greeting) .append(",\n\tinterval=").append(interval) .append(",\n\tprecision=").append(precision) .append(",\n\tservers=").append(servers) .append(",\n\tenvironments=").append(environments) .append("\n}"); return rv.toString(); } }
src/main/java/de/springbootbuch/extconfig/ExampleProperties.java
package de.springbootbuch.extconfig; import java.net.URL; import java.util.List; import java.util.Map; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties("example") public class ExampleProperties { public static class Server { /** The name of the server. */ private String name; /** The URL of the server. */ private URL url; public String getName() { return name; } public void setName(String name) { this.name = name; } public URL getUrl() { return url; } public void setUrl(URL url) { this.url = url; } @Override public String toString() { return "Server{" + "name=" + name + ", url=" + url + '}'; } } public static enum Environment { dev, prod, cloud } /** The greeting used. */ @NotNull @Size(min = 1) private String greeting; /** Some arbitrary interval. */ @Min(10) private Integer interval; /** An example of maps. */ private Map<Environment, Map<String, Object>> environments; /** The list of servers. */ private List<Server> servers; /** A precision. */ private Double precision; public String getGreeting() { return greeting; } public void setGreeting(String greeting) { this.greeting = greeting; } public Integer getInterval() { return interval; } public void setInterval(Integer interval) { this.interval = interval; } public Map<Environment, Map<String, Object>> getEnvironments() { return environments; } public void setEnvironments(Map<Environment, Map<String, Object>> environments) { this.environments = environments; } public List<Server> getServers() { return servers; } public void setServers(List<Server> servers) { this.servers = servers; } public Double getPrecision() { return precision; } public void setPrecision(Double precision) { this.precision = precision; } @Override public String toString() { final StringBuilder rv = new StringBuilder(); rv .append("ExampleProperties{") .append("\n\tgreeting=").append(greeting) .append(",\n\tinterval=").append(interval) .append(",\n\tprecision=").append(precision) .append(",\n\tservers=").append(servers) .append(",\n\tenvironments=").append(environments) .append("\n}"); return rv.toString(); } }
Format
src/main/java/de/springbootbuch/extconfig/ExampleProperties.java
Format
Java
apache-2.0
cf1d7a11f18b6a84d0a7fd4ddff47fa7b7697d36
0
UweTrottmann/trakt-java
package com.jakewharton.trakt.services; import java.util.Date; import java.util.List; import com.google.gson.reflect.TypeToken; import com.jakewharton.trakt.TraktApiBuilder; import com.jakewharton.trakt.TraktApiService; import com.jakewharton.trakt.entities.ActivityItem; import com.jakewharton.trakt.entities.ActivityItemBase; import com.jakewharton.trakt.entities.CalendarDate; import com.jakewharton.trakt.entities.Movie; import com.jakewharton.trakt.entities.TvShow; import com.jakewharton.trakt.entities.UserProfile; import com.jakewharton.trakt.enumerations.ExtendedParam; public final class UserService extends TraktApiService { /** * Returns a users shows airing during the time period specified. Protected * users won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public CalendarShowsBuilder calendarShows(String username) { return new CalendarShowsBuilder(this, username); } /** * Returns the TV show episode or movie a user is currently watching. If * they aren't watching anything, a blank object will be returned. * Protected users won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public WatchingBuilder watching(String username) { return new WatchingBuilder(this, username); } /** @deprecated Use {@link ActivityService#user(String)} */ @Deprecated public WatchedBuilder watched(String username) { return new WatchedBuilder(this, username); } /** @deprecated Use {@link ActivityService#user(String) */ @Deprecated public WatchedEpisodesBuilder watchedEpisodes(String username) { return new WatchedEpisodesBuilder(this, username); } /** @deprecated Use {@link ActivityService#user(String) */ @Deprecated public WatchedMoviesBuilder watchedMovies(String username) { return new WatchedMoviesBuilder(this, username); } /** * Returns all episodes in a user's watchlist. Each show will have its own * entry and will contain all episodes in the watchlist. Protected users * won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public WatchlistEpisodesBuilder watchlistEpisodes(String username) { return new WatchlistEpisodesBuilder(this, username); } /** * Returns all movies in a user's watchlist. Each movie will indicate when * it was added to the watchlist. Protected users won't return any data * unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public WatchlistMoviesBuilder watchlistMovies(String username) { return new WatchlistMoviesBuilder(this, username); } /** * Returns all shows in a user's watchlist. Each show will indicate when it * was added to the watchlist. Protected users won't return any data unless * you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public WatchlistShowsBuilder watchlistShows(String username) { return new WatchlistShowsBuilder(this, username); } /** * Returns profile information for a user. Protected users won't return any * data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public ProfileBuilder profile(String username) { return new ProfileBuilder(this, username); } /** * Returns an array of the user's friends. Each friend has the detailed * profile including what they are currently watching and their recent * watches. Protected users won't return any data unless you are friends. * Any friends of the main user that are protected won't display data * either. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public FriendsBuilder friends(String username) { return new FriendsBuilder(this, username); } /** * Returns all movies in a user's library. Each movie will indicate if it's * in the user's collection and how many plays it has. Protected users * won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryMoviesAllBuilder libraryMoviesAll(String username) { return new LibraryMoviesAllBuilder(this, username); } /** * Returns all movies in a user's library collection. Collection items * might include Blu-rays, DVDs, and digital downloads. Protected users * won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryMoviesCollectionBuilder libraryMoviesCollection(String username) { return new LibraryMoviesCollectionBuilder(this, username); } /** * Returns all movies a user has hated. Protected users won't return any * data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryMoviesHatedBuilder libraryMoviesHated(String username) { return new LibraryMoviesHatedBuilder(this, username); } /** * Returns all movies a user has loved. Protected users won't return any * data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryMoviesLovedBuilder libraryMoviesLoved(String username) { return new LibraryMoviesLovedBuilder(this, username); } /** * Returns all movies that a user has watched. This method is useful to sync * trakt's data with local media center. Protected users won't return any * data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryMoviesWatchedBuilder libraryMoviesWatched(String username) { return new LibraryMoviesWatchedBuilder(this, username); } /** * Returns all shows in a user's library. Each show will indicate how many * plays it has. Protected users won't return any data unless you are * friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryShowsAllBuilder libraryShowsAll(String username) { return new LibraryShowsAllBuilder(this, username); } /** * Returns all shows and episodes in a user's library collection. * Collection items might include Blu-rays, DVDs, and digital downloads. * Protected users won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryShowsCollectionBuilder libraryShowsCollection(String username) { return new LibraryShowsCollectionBuilder(this, username); } /** * Returns all shows a user has hated. Protected users won't return any * data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryShowsHatedBuilder libraryShowsHated(String username) { return new LibraryShowsHatedBuilder(this, username); } /** * Returns all shows a user has loved. Protected users won't return any * data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryShowsLovedBuilder libraryShowsLoved(String username) { return new LibraryShowsLovedBuilder(this, username); } /** * Returns all shows and episodes that a user has watched. This method is * useful to sync trakt's data with local media center. Protected users * won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryShowsWatchedBuilder libraryShowsWatched(String username) { return new LibraryShowsWatchedBuilder(this, username); } /** * Returns list details and all items it contains. Protected users won't * return any data unless you are friends. To view your own private lists, * you will need to authenticate as yourself. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @param slug Valid list slug for this user. You can get all slugs from * the user/lists method. * @return Builder instance. */ public ListBuilder list(String username, String slug) { return new ListBuilder(this).username(username).slug(slug); } /** * Returns all custom lists for a user. Protected users won't return any * data unless you are friends. To view your own private lists, you will * need to authenticate as yourself. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public ListsBuilder lists(String username) { return new ListsBuilder(this).username(username); } public static final class CalendarShowsBuilder extends TraktApiBuilder<List<CalendarDate>> { private static final int DEFAULT_DAYS = 7; private static final String URI = "/user/calendar/shows.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_DATE + "/" + FIELD_DAYS; private CalendarShowsBuilder(UserService service, String username) { super(service, new TypeToken<List<CalendarDate>>() {}, URI); this.field(FIELD_USERNAME, username); } /** * Start date for the calendar. * * @param date Value. * @return Builder instance. */ public CalendarShowsBuilder date(Date date) { this.field(FIELD_DATE, date); if (!this.hasField(FIELD_DAYS)) { //Set default. this.field(FIELD_DAYS, DEFAULT_DAYS); } return this; } /** * Number of days to display starting from the date. * * @param days Value. * @return Builder instance. */ public CalendarShowsBuilder days(int days) { this.field(FIELD_DAYS, days); if (!this.hasField(FIELD_DATE)) { //Set default. this.field(FIELD_DATE, new Date()); } return this; } } public static final class WatchingBuilder extends TraktApiBuilder<ActivityItemBase> { private static final String URI = "/user/watching.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchingBuilder(UserService service, String username) { super(service, new TypeToken<ActivityItemBase>() {}, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchedBuilder extends TraktApiBuilder<List<ActivityItem>> { private static final String URI = "/user/watched.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchedBuilder(UserService service, String username) { super(service, new TypeToken<List<ActivityItem>>() {}, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchedEpisodesBuilder extends TraktApiBuilder<List<ActivityItem>> { private static final String URI = "/user/watched/episodes.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchedEpisodesBuilder(UserService service, String username) { super(service, new TypeToken<List<ActivityItem>>() {}, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchedMoviesBuilder extends TraktApiBuilder<List<ActivityItem>> { private static final String URI = "/user/watched/movies.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchedMoviesBuilder(UserService service, String username) { super(service, new TypeToken<List<ActivityItem>>() {}, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchlistEpisodesBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/watchlist/episodes.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchlistEpisodesBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() {}, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchlistMoviesBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/watchlist/movies.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchlistMoviesBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() {}, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchlistShowsBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/watchlist/shows.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchlistShowsBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() {}, URI); this.field(FIELD_USERNAME, username); } } public static final class ProfileBuilder extends TraktApiBuilder<UserProfile> { private static final String URI = "/user/profile.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private ProfileBuilder(UserService service, String username) { super(service, new TypeToken<UserProfile>() {}, URI); this.field(FIELD_USERNAME, username); } } public static final class FriendsBuilder extends TraktApiBuilder<List<UserProfile>> { private static final String URI = "/user/friends.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private FriendsBuilder(UserService service, String username) { super(service, new TypeToken<List<UserProfile>>() {}, URI); this.field(FIELD_USERNAME, username); } } public static final class LibraryMoviesAllBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/library/movies/all.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryMoviesAllBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() {}, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tmdb_id, * plays, in_collection, unseen) required for media center syncing if * set to min. This sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryMoviesAllBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryMoviesCollectionBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/library/movies/collection.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryMoviesCollectionBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() {}, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tmdb_id) * required for media center syncing if set to min. This sends about * half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryMoviesCollectionBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryMoviesHatedBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/library/movies/hated.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryMoviesHatedBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() {}, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tmdb_id) * required for media center syncing if set to min. This sends about * half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryMoviesHatedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryMoviesLovedBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/library/movies/loved.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryMoviesLovedBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() {}, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tmdb_id) * required for media center syncing if set to min. This sends about * half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryMoviesLovedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryMoviesWatchedBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/library/movies/watched.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryMoviesWatchedBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tmdb_id, * plays) required for media center syncing if set to min. This sends * about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryMoviesWatchedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryShowsAllBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/library/shows/all.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryShowsAllBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() {}, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tvdb_id, * tvrage_id, plays) required for media center syncing if set to min. * This sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryShowsAllBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryShowsCollectionBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/library/shows/collection.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryShowsCollectionBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() {}, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tvdb_id, * tvrage_id, seasons) required for media center syncing if set to min. * This sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryShowsCollectionBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryShowsHatedBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/library/shows/hated.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryShowsHatedBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() {}, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tvdb_id, * tvrage_id) required for media center syncing if set to min. This * sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryShowsHatedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryShowsLovedBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/library/shows/loved.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryShowsLovedBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() {}, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tvdb_id, * tvrage_id) required for media center syncing if set to min. This * sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryShowsLovedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryShowsWatchedBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/library/shows/watched.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryShowsWatchedBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() {}, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete show info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tvdb_id, * tvrage_id, seasons) required for media center syncing if set to Min. * This sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryShowsWatchedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class ListBuilder extends TraktApiBuilder<com.jakewharton.trakt.entities.List> { private static final String URI = "/user/list.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_SLUG; private ListBuilder(UserService service) { super(service, new TypeToken<com.jakewharton.trakt.entities.List>() {}, URI); } /** * Valid list slug for this user. You can get all slugs from the * user/lists method. * * @param slug Value. * @return Builder instance. */ public ListBuilder slug(String slug) { super.field(FIELD_SLUG, slug); return this; } /** * You can get a username by browsing the website and looking at the * URL when on a profile page. * * @param username Value. * @return Builder instance. */ public ListBuilder username(String username) { super.field(FIELD_USERNAME, username); return this; } } public static final class ListsBuilder extends TraktApiBuilder<List<com.jakewharton.trakt.entities.List>> { private static final String URI = "/user/lists.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private ListsBuilder(UserService service) { super(service, new TypeToken<List<com.jakewharton.trakt.entities.List>>() {}, URI); } /** * You can get a username by browsing the website and looking at the * URL when on a profile page. * * @param username Value. * @return Builder instance. */ public ListsBuilder username(String username) { super.field(FIELD_USERNAME, username); return this; } } }
src/main/java/com/jakewharton/trakt/services/UserService.java
package com.jakewharton.trakt.services; import com.google.gson.reflect.TypeToken; import com.jakewharton.trakt.TraktApiBuilder; import com.jakewharton.trakt.TraktApiService; import com.jakewharton.trakt.entities.ActivityItem; import com.jakewharton.trakt.entities.ActivityItemBase; import com.jakewharton.trakt.entities.CalendarDate; import com.jakewharton.trakt.entities.Movie; import com.jakewharton.trakt.entities.TvShow; import com.jakewharton.trakt.entities.UserProfile; import com.jakewharton.trakt.enumerations.ExtendedParam; import java.util.Date; import java.util.List; public final class UserService extends TraktApiService { /** * Returns a users shows airing during the time period specified. Protected * users won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public CalendarShowsBuilder calendarShows(String username) { return new CalendarShowsBuilder(this, username); } /** * Returns the TV show episode or movie a user is currently watching. If * they aren't watching anything, a blank object will be returned. Protected * users won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public WatchingBuilder watching(String username) { return new WatchingBuilder(this, username); } /** @deprecated Use {@link ActivityService#user(String)} */ @Deprecated public WatchedBuilder watched(String username) { return new WatchedBuilder(this, username); } /** @deprecated Use {@link ActivityService#user(String) */ @Deprecated public WatchedEpisodesBuilder watchedEpisodes(String username) { return new WatchedEpisodesBuilder(this, username); } /** @deprecated Use {@link ActivityService#user(String) */ @Deprecated public WatchedMoviesBuilder watchedMovies(String username) { return new WatchedMoviesBuilder(this, username); } /** * Returns all episodes in a user's watchlist. Each show will have its own * entry and will contain all episodes in the watchlist. Protected users * won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public WatchlistEpisodesBuilder watchlistEpisodes(String username) { return new WatchlistEpisodesBuilder(this, username); } /** * Returns all movies in a user's watchlist. Each movie will indicate when * it was added to the watchlist. Protected users won't return any data * unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public WatchlistMoviesBuilder watchlistMovies(String username) { return new WatchlistMoviesBuilder(this, username); } /** * Returns all shows in a user's watchlist. Each show will indicate when it * was added to the watchlist. Protected users won't return any data unless * you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public WatchlistShowsBuilder watchlistShows(String username) { return new WatchlistShowsBuilder(this, username); } /** * Returns profile information for a user. Protected users won't return any * data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public ProfileBuilder profile(String username) { return new ProfileBuilder(this, username); } /** * Returns an array of the user's friends. Each friend has the detailed * profile including what they are currently watching and their recent * watches. Protected users won't return any data unless you are friends. * Any friends of the main user that are protected won't display data * either. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public FriendsBuilder friends(String username) { return new FriendsBuilder(this, username); } /** * Returns all movies in a user's library. Each movie will indicate if it's * in the user's collection and how many plays it has. Protected users won't * return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryMoviesAllBuilder libraryMoviesAll(String username) { return new LibraryMoviesAllBuilder(this, username); } /** * Returns all movies in a user's library collection. Collection items might * include Blu-rays, DVDs, and digital downloads. Protected users won't * return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryMoviesCollectionBuilder libraryMoviesCollection(String username) { return new LibraryMoviesCollectionBuilder(this, username); } /** * Returns all movies a user has hated. Protected users won't return any * data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryMoviesHatedBuilder libraryMoviesHated(String username) { return new LibraryMoviesHatedBuilder(this, username); } /** * Returns all movies a user has loved. Protected users won't return any * data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryMoviesLovedBuilder libraryMoviesLoved(String username) { return new LibraryMoviesLovedBuilder(this, username); } /** * Returns all movies that a user has watched. This method is useful to sync * trakt's data with local media center. Protected users won't return any * data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryMoviesWatchedBuilder libraryMoviesWatched(String username) { return new LibraryMoviesWatchedBuilder(this, username); } /** * Returns all shows in a user's library. Each show will indicate how many * plays it has. Protected users won't return any data unless you are * friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryShowsAllBuilder libraryShowsAll(String username) { return new LibraryShowsAllBuilder(this, username); } /** * Returns all shows and episodes in a user's library collection. Collection * items might include Blu-rays, DVDs, and digital downloads. Protected * users won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryShowsCollectionBuilder libraryShowsCollection(String username) { return new LibraryShowsCollectionBuilder(this, username); } /** * Returns all shows a user has hated. Protected users won't return any data * unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryShowsHatedBuilder libraryShowsHated(String username) { return new LibraryShowsHatedBuilder(this, username); } /** * Returns all shows a user has loved. Protected users won't return any data * unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryShowsLovedBuilder libraryShowsLoved(String username) { return new LibraryShowsLovedBuilder(this, username); } /** * Returns all shows and episodes that a user has watched. This method is * useful to sync trakt's data with local media center. Protected users * won't return any data unless you are friends. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public LibraryShowsWatchedBuilder libraryShowsWatched(String username) { return new LibraryShowsWatchedBuilder(this, username); } /** * Returns list details and all items it contains. Protected users won't * return any data unless you are friends. To view your own private lists, * you will need to authenticate as yourself. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @param slug Valid list slug for this user. You can get all slugs from the * user/lists method. * @return Builder instance. */ public ListBuilder list(String username, String slug) { return new ListBuilder(this).username(username).slug(slug); } /** * Returns all custom lists for a user. Protected users won't return any * data unless you are friends. To view your own private lists, you will * need to authenticate as yourself. * * @param username You can get a username by browsing the website and * looking at the URL when on a profile page. * @return Builder instance. */ public ListsBuilder lists(String username) { return new ListsBuilder(this).username(username); } public static final class CalendarShowsBuilder extends TraktApiBuilder<List<CalendarDate>> { private static final int DEFAULT_DAYS = 7; private static final String URI = "/user/calendar/shows.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_DATE + "/" + FIELD_DAYS; private CalendarShowsBuilder(UserService service, String username) { super(service, new TypeToken<List<CalendarDate>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Start date for the calendar. * * @param date Value. * @return Builder instance. */ public CalendarShowsBuilder date(Date date) { this.field(FIELD_DATE, date); if (!this.hasField(FIELD_DAYS)) { // Set default. this.field(FIELD_DAYS, DEFAULT_DAYS); } return this; } /** * Number of days to display starting from the date. * * @param days Value. * @return Builder instance. */ public CalendarShowsBuilder days(int days) { this.field(FIELD_DAYS, days); if (!this.hasField(FIELD_DATE)) { // Set default. this.field(FIELD_DATE, new Date()); } return this; } } public static final class WatchingBuilder extends TraktApiBuilder<ActivityItemBase> { private static final String URI = "/user/watching.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchingBuilder(UserService service, String username) { super(service, new TypeToken<ActivityItemBase>() { }, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchedBuilder extends TraktApiBuilder<List<ActivityItem>> { private static final String URI = "/user/watched.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchedBuilder(UserService service, String username) { super(service, new TypeToken<List<ActivityItem>>() { }, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchedEpisodesBuilder extends TraktApiBuilder<List<ActivityItem>> { private static final String URI = "/user/watched/episodes.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchedEpisodesBuilder(UserService service, String username) { super(service, new TypeToken<List<ActivityItem>>() { }, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchedMoviesBuilder extends TraktApiBuilder<List<ActivityItem>> { private static final String URI = "/user/watched/movies.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchedMoviesBuilder(UserService service, String username) { super(service, new TypeToken<List<ActivityItem>>() { }, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchlistEpisodesBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/watchlist/episodes.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchlistEpisodesBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() { }, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchlistMoviesBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/watchlist/movies.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchlistMoviesBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() { }, URI); this.field(FIELD_USERNAME, username); } } public static final class WatchlistShowsBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/watchlist/shows.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private WatchlistShowsBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() { }, URI); this.field(FIELD_USERNAME, username); } } public static final class ProfileBuilder extends TraktApiBuilder<UserProfile> { private static final String URI = "/user/profile.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private ProfileBuilder(UserService service, String username) { super(service, new TypeToken<UserProfile>() { }, URI); this.field(FIELD_USERNAME, username); } } public static final class FriendsBuilder extends TraktApiBuilder<List<UserProfile>> { private static final String URI = "/user/friends.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private FriendsBuilder(UserService service, String username) { super(service, new TypeToken<List<UserProfile>>() { }, URI); this.field(FIELD_USERNAME, username); } } public static final class LibraryMoviesAllBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/library/movies/all.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryMoviesAllBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tmdb_id, * plays, in_collection, unseen) required for media center syncing if * set to min. This sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryMoviesAllBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryMoviesCollectionBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/library/movies/collection.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryMoviesCollectionBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tmdb_id) * required for media center syncing if set to min. This sends about * half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryMoviesCollectionBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryMoviesHatedBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/library/movies/hated.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryMoviesHatedBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tmdb_id) * required for media center syncing if set to min. This sends about * half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryMoviesHatedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryMoviesLovedBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/library/movies/loved.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryMoviesLovedBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tmdb_id) * required for media center syncing if set to min. This sends about * half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryMoviesLovedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryMoviesWatchedBuilder extends TraktApiBuilder<List<Movie>> { private static final String URI = "/user/library/movies/watched.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryMoviesWatchedBuilder(UserService service, String username) { super(service, new TypeToken<List<Movie>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tmdb_id, * plays) required for media center syncing if set to min. This sends * about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryMoviesWatchedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryShowsAllBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/library/shows/all.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryShowsAllBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tvdb_id, * tvrage_id, plays) required for media center syncing if set to min. * This sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryShowsAllBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryShowsCollectionBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/library/shows/collection.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryShowsCollectionBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tvdb_id, * tvrage_id, seasons) required for media center syncing if set to min. * This sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryShowsCollectionBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryShowsHatedBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/library/shows/hated.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryShowsHatedBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tvdb_id, * tvrage_id) required for media center syncing if set to min. This * sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryShowsHatedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryShowsLovedBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/library/shows/loved.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryShowsLovedBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete movie info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tvdb_id, * tvrage_id) required for media center syncing if set to min. This * sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryShowsLovedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class LibraryShowsWatchedBuilder extends TraktApiBuilder<List<TvShow>> { private static final String URI = "/user/library/shows/watched.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_EXTENDED; private LibraryShowsWatchedBuilder(UserService service, String username) { super(service, new TypeToken<List<TvShow>>() { }, URI); this.field(FIELD_USERNAME, username); } /** * Returns complete show info if set to Extended. Only send this if you * really need the full dump as it doubles the data size being sent * back. Returns only the minimal info (title, year, imdb_id, tvdb_id, * tvrage_id, seasons) required for media center syncing if set to Min. * This sends about half the data. * * @param ExtendedParam * @return Builder instance */ public LibraryShowsWatchedBuilder extended(ExtendedParam extended) { this.field(FIELD_EXTENDED, extended.toString()); return this; } } public static final class ListBuilder extends TraktApiBuilder<com.jakewharton.trakt.entities.List> { private static final String URI = "/user/list.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME + "/" + FIELD_SLUG; private ListBuilder(UserService service) { super(service, new TypeToken<com.jakewharton.trakt.entities.List>() { }, URI); } /** * Valid list slug for this user. You can get all slugs from the * user/lists method. * * @param slug Value. * @return Builder instance. */ public ListBuilder slug(String slug) { super.field(FIELD_SLUG, slug); return this; } /** * You can get a username by browsing the website and looking at the URL * when on a profile page. * * @param username Value. * @return Builder instance. */ public ListBuilder username(String username) { super.field(FIELD_USERNAME, username); return this; } } public static final class ListsBuilder extends TraktApiBuilder<List<com.jakewharton.trakt.entities.List>> { private static final String URI = "/user/lists.json/" + FIELD_API_KEY + "/" + FIELD_USERNAME; private ListsBuilder(UserService service) { super(service, new TypeToken<List<com.jakewharton.trakt.entities.List>>() { }, URI); } /** * You can get a username by browsing the website and looking at the URL * when on a profile page. * * @param username Value. * @return Builder instance. */ public ListsBuilder username(String username) { super.field(FIELD_USERNAME, username); return this; } } }
Fix indentation.
src/main/java/com/jakewharton/trakt/services/UserService.java
Fix indentation.
Java
apache-2.0
ef3a746b00431590cede70fb18b11010079a899f
0
jordw/heftydb
/* * Copyright (c) 2014. Jordan Williams * * 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.jordanwilliams.heftydb.metrics; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.Counter; import com.codahale.metrics.Histogram; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.codahale.metrics.UniformReservoir; import com.jordanwilliams.heftydb.db.Config; import java.util.concurrent.TimeUnit; public class Metrics { private static final String METRIC_PREFIX = "heftydb."; private final MetricRegistry metrics = new MetricRegistry(); private final ConsoleReporter consoleReporter; public Metrics(Config config) { this.consoleReporter = ConsoleReporter.forRegistry(metrics).convertDurationsTo(TimeUnit.MILLISECONDS) .convertRatesTo(TimeUnit.SECONDS).build(); consoleReporter.start(30, TimeUnit.SECONDS); initMetrics(); } public Counter counter(String name) { return metrics.counter(metricName(name)); } public Meter meter(String name) { return metrics.meter(metricName(name)); } public CacheHitGauge hitGauge(String name) { return (CacheHitGauge) metrics.getGauges().get(metricName(name)); } public Histogram histogram(String name) { return metrics.histogram(metricName(name)); } public Timer timer(String name) { return metrics.timer(metricName(name)); } private void initMetrics() { //Main DB Metrics metrics.register(metricName("write"), new Timer(new UniformReservoir())); metrics.register(metricName("write.rate"), new Meter()); metrics.register(metricName("read"), new Timer(new UniformReservoir())); metrics.register(metricName("read.rate"), new Meter()); metrics.register(metricName("scan"), new Timer(new UniformReservoir())); metrics.register(metricName("scan.rate"), new Meter()); //Write metrics.register(metricName("write.concurrentMemoryTableSerializers"), new Histogram(new UniformReservoir())); metrics.register(metricName("write.memoryTableSerialize"), new Timer(new UniformReservoir())); //Read metrics.register(metricName("read.tablesConsulted"), new Histogram(new UniformReservoir())); metrics.register(metricName("read.bloomFilterFalsePositiveRate"), new CacheHitGauge()); //FileTable metrics.register(metricName("table.cacheHitRate"), new CacheHitGauge()); //Index metrics.register(metricName("index.searchLevels"), new Histogram(new UniformReservoir())); metrics.register(metricName("index.cacheHitRate"), new CacheHitGauge()); //Compactor metrics.register(metricName("compactor.concurrentTasks"), new Histogram(new UniformReservoir())); metrics.register(metricName("compactor.taskExecution"), new Timer(new UniformReservoir())); metrics.register(metricName("compactor.rate"), new Meter()); } private static String metricName(String name) { return METRIC_PREFIX + name; } }
src/main/java/com/jordanwilliams/heftydb/metrics/Metrics.java
/* * Copyright (c) 2014. Jordan Williams * * 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.jordanwilliams.heftydb.metrics; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.Counter; import com.codahale.metrics.Histogram; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.codahale.metrics.UniformReservoir; import com.jordanwilliams.heftydb.db.Config; import java.util.concurrent.TimeUnit; public class Metrics { private static final String METRIC_PREFIX = "heftydb."; private final MetricRegistry metrics = new MetricRegistry(); private final ConsoleReporter consoleReporter; public Metrics(Config config) { this.consoleReporter = ConsoleReporter.forRegistry(metrics).convertDurationsTo(TimeUnit.MILLISECONDS) .convertRatesTo(TimeUnit.SECONDS).build(); consoleReporter.start(30, TimeUnit.SECONDS); initMetrics(); } public Counter counter(String name) { return metrics.counter(metricName(name)); } public Meter meter(String name) { return metrics.meter(metricName(name)); } public CacheHitGauge hitGauge(String name) { return (CacheHitGauge) metrics.getGauges().get(metricName(name)); } public Histogram histogram(String name) { return metrics.histogram(metricName(name)); } public Timer timer(String name) { return metrics.timer(metricName(name)); } private void initMetrics() { //Main DB Metrics metrics.register(metricName("write"), new Timer()); metrics.register(metricName("write.rate"), new Meter()); metrics.register(metricName("read"), new Timer()); metrics.register(metricName("read.rate"), new Meter()); metrics.register(metricName("scan"), new Timer()); metrics.register(metricName("scan.rate"), new Meter()); //Write metrics.register(metricName("write.concurrentMemoryTableSerializers"), new Histogram(new UniformReservoir())); metrics.register(metricName("write.memoryTableSerialize"), new Timer()); //Read metrics.register(metricName("read.tablesConsulted"), new Histogram(new UniformReservoir())); metrics.register(metricName("read.bloomFilterFalsePositiveRate"), new CacheHitGauge()); //FileTable metrics.register(metricName("table.cacheHitRate"), new CacheHitGauge()); //Index metrics.register(metricName("index.searchLevels"), new Histogram(new UniformReservoir())); metrics.register(metricName("index.cacheHitRate"), new CacheHitGauge()); //Compactor metrics.register(metricName("compactor.concurrentTasks"), new Histogram(new UniformReservoir())); metrics.register(metricName("compactor.taskExecution"), new Timer()); metrics.register(metricName("compactor.rate"), new Meter()); } private static String metricName(String name) { return METRIC_PREFIX + name; } }
Eliminate memory heavy sample reservoirs
src/main/java/com/jordanwilliams/heftydb/metrics/Metrics.java
Eliminate memory heavy sample reservoirs
Java
apache-2.0
7742fc0d0e185c867221d5cab3378328a1a5d8b9
0
mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid
/* * 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.usergrid.corepersistence.asyncevents.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.usergrid.persistence.collection.serialization.impl.migration.EntityIdScope; import org.apache.usergrid.persistence.core.scope.ApplicationScope; import org.apache.usergrid.persistence.graph.Edge; import org.apache.usergrid.persistence.model.entity.Id; /** * Created by Jeff West on 5/25/15. */ @JsonIgnoreProperties(ignoreUnknown = true) public class AsyncEvent { @JsonProperty protected EventType eventType; @JsonProperty protected EntityIdScope entityIdScope; @JsonProperty protected ApplicationScope applicationScope; @JsonProperty protected Id entityId; @JsonProperty protected Edge edge; /** * required for jackson, do not delete */ protected AsyncEvent() { } public AsyncEvent(final EventType eventType, final EntityIdScope entityIdScope) { this.eventType = eventType; this.entityIdScope = entityIdScope; } public AsyncEvent(EventType eventType, ApplicationScope applicationScope, Edge edge) { this.eventType = eventType; this.applicationScope = applicationScope; this.edge = edge; } public AsyncEvent(EventType eventType, ApplicationScope applicationScope, Id entityId, Edge edge) { this.eventType = eventType; this.applicationScope = applicationScope; this.edge = edge; this.entityId = entityId; } public final Id getEntityId() { return entityId; } protected void setEntityId(Id entityId) { this.entityId = entityId; } public final EventType getEventType() { return eventType; } protected void setEventType(EventType eventType) { this.eventType = eventType; } public EntityIdScope getEntityIdScope() { return entityIdScope; } protected void setEntityIdScope(EntityIdScope entityIdScope) { this.entityIdScope = entityIdScope; } public ApplicationScope getApplicationScope() { return applicationScope; } protected void setApplicationScope(ApplicationScope applicationScope) { this.applicationScope = applicationScope; } public Edge getEdge() { return edge; } protected void setEdge(Edge edge) { this.edge = edge; } public enum EventType { EDGE_DELETE, EDGE_INDEX, ENTITY_DELETE, ENTITY_INDEX; public String asString() { return toString(); } } }
stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/model/AsyncEvent.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.usergrid.corepersistence.asyncevents.model; import org.apache.usergrid.persistence.collection.serialization.impl.migration.EntityIdScope; import org.apache.usergrid.persistence.core.scope.ApplicationScope; import org.apache.usergrid.persistence.graph.Edge; import org.apache.usergrid.persistence.model.entity.Id; /** * Created by Jeff West on 5/25/15. */ public class AsyncEvent { protected EventType eventType; protected EntityIdScope entityIdScope; protected ApplicationScope applicationScope; protected Id entityId; protected Edge edge; /** * required for jackson, do not delete */ protected AsyncEvent() { } public AsyncEvent(final EventType eventType, final EntityIdScope entityIdScope) { this.eventType = eventType; this.entityIdScope = entityIdScope; } public AsyncEvent(EventType eventType, ApplicationScope applicationScope, Edge edge) { this.eventType = eventType; this.applicationScope = applicationScope; this.edge = edge; } public AsyncEvent(EventType eventType, ApplicationScope applicationScope, Id entityId, Edge edge) { this.eventType = eventType; this.applicationScope = applicationScope; this.edge = edge; this.entityId = entityId; } public final Id getEntityId() { return entityId; } protected void setEntityId(Id entityId) { this.entityId = entityId; } public final EventType getEventType() { return eventType; } protected void setEventType(EventType eventType) { this.eventType = eventType; } public EntityIdScope getEntityIdScope() { return entityIdScope; } protected void setEntityIdScope(EntityIdScope entityIdScope) { this.entityIdScope = entityIdScope; } public ApplicationScope getApplicationScope() { return applicationScope; } protected void setApplicationScope(ApplicationScope applicationScope) { this.applicationScope = applicationScope; } public Edge getEdge() { return edge; } protected void setEdge(Edge edge) { this.edge = edge; } public enum EventType { EDGE_DELETE, EDGE_INDEX, ENTITY_DELETE, ENTITY_INDEX; public String asString() { return toString(); } } }
Added JsonFactory annotations for attributes
stack/core/src/main/java/org/apache/usergrid/corepersistence/asyncevents/model/AsyncEvent.java
Added JsonFactory annotations for attributes
Java
apache-2.0
b945bb1218b87436f905a207bdaabb87f7165d00
0
Ravmouse/vvasilyev,Ravmouse/vvasilyev,Ravmouse/vvasilyev
package ru.job4j.h1io.t3scanfilesys; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @author Vitaly Vasilyev, date: 03.03.2019, e-mail: rav.energ@rambler.ru * @version 1.0 */ public class Search { /** * @param parent путь до каталога, с которого нужно осуществлять поиск. * @param exts список расширений файлов, которых мы хотим найти. * @return список файлов. */ public static List<File> files(String parent, List<String> exts) { final List<File> files = new ArrayList<>(); final Queue<File> queue = new LinkedList<>(); queue.offer(new File(parent)); while (!queue.isEmpty()) { final File file = queue.poll(); if (!file.isDirectory()) { for (String s : exts) { if (file.getName().substring(file.getName().lastIndexOf(".") + 1).equals(s)) { files.add(file); } } } else { for (File f : file.listFiles()) { queue.offer(f); } } } return files; } }
chapter_009/src/main/java/ru/job4j/h1io/t3scanfilesys/Search.java
package ru.job4j.h1io.t3scanfilesys; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @author Vitaly Vasilyev, date: 03.03.2019, e-mail: rav.energ@rambler.ru * @version 1.0 */ public class Search { /** * @param parent путь до каталога, с которого нужно осуществлять поиск. * @param exts список расширений файлов, которых мы хотим найти. * @return список файлов. */ public static List<File> files(String parent, List<String> exts) { final List<File> files = new ArrayList<>(); final Queue<File> queue = new LinkedList<>(); queue.offer(new File(parent)); while (!queue.isEmpty()) { final File file = queue.poll(); if (!file.isDirectory()) { for (String s : exts) { if (file.getName().contains(s)) { files.add(file); } } } else { for (File f : file.listFiles()) { queue.offer(f); } } } return files; } }
9.3. Сканирование файловой системы [#106929] (исправления).
chapter_009/src/main/java/ru/job4j/h1io/t3scanfilesys/Search.java
9.3. Сканирование файловой системы [#106929] (исправления).
Java
apache-2.0
62907283eecdf6d88372f643231d7e7c66378576
0
apache/derby,apache/derby,trejkaz/derby,apache/derby,trejkaz/derby,trejkaz/derby,apache/derby
/* Derby - Class org.apache.derby.iapi.db.PropertyInfo 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.derby.iapi.db; import org.apache.derby.iapi.error.PublicAPI; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.sql.Activation; import org.apache.derby.iapi.sql.conn.Authorizer; import org.apache.derby.iapi.sql.conn.LanguageConnectionContext; import org.apache.derby.iapi.sql.conn.ConnectionUtil; import org.apache.derby.iapi.store.access.TransactionController; import java.sql.SQLException; /** * PropertyInfo is a class with static methods that set properties associated with a database. * * * <P> This class can only be used within an SQL-J statement, a Java procedure or a server side Java method. <p>This class can be accessed using the class alias <code> PROPERTYINFO </code> in SQL-J statements. */ public final class PropertyInfo { /** Set or delete the value of a property of the database on the current connection. @param key the property key @param value the new value, if null the property is deleted. @exception SQLException on error */ public static void setDatabaseProperty(String key, String value) throws SQLException { LanguageConnectionContext lcc = ConnectionUtil.getCurrentLCC(); try { Authorizer a = lcc.getAuthorizer(); a.authorize((Activation) null, Authorizer.PROPERTY_WRITE_OP); // Get the current transaction controller TransactionController tc = lcc.getTransactionExecute(); tc.setProperty(key, value, false); } catch (StandardException se) { throw PublicAPI.wrapStandardException(se); } } private PropertyInfo() {} }
java/engine/org/apache/derby/iapi/db/PropertyInfo.java
/* Derby - Class org.apache.derby.iapi.db.PropertyInfo 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.derby.iapi.db; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.error.PublicAPI; import org.apache.derby.iapi.sql.Activation; import org.apache.derby.iapi.sql.conn.Authorizer; import org.apache.derby.iapi.sql.conn.LanguageConnectionContext; import org.apache.derby.iapi.sql.conn.ConnectionUtil; import org.apache.derby.iapi.sql.dictionary.ConglomerateDescriptor; import org.apache.derby.iapi.sql.dictionary.DataDictionary; import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor; import org.apache.derby.iapi.sql.dictionary.TableDescriptor; import org.apache.derby.iapi.store.access.ConglomerateController; import org.apache.derby.iapi.store.access.TransactionController; import org.apache.derby.iapi.services.property.PropertyUtil; import java.util.Properties; import java.sql.SQLException; /** * PropertyInfo is a class with static methods that retrieve the properties * associated with a table or index and set and retrieve properties associated * with a database. * * <P> This class can only be used within an SQL-J statement, a Java procedure or a server side Java method. <p>This class can be accessed using the class alias <code> PROPERTYINFO </code> in SQL-J statements. */ public final class PropertyInfo { /** * Get the Properties associated with a given table. * * @param schemaName The name of the schema that the table is in. * @param tableName The name of the table. * * @return Properties The Properties associated with the specified table. * (An empty Properties is returned if the table does not exist.) * @exception SQLException on error */ public static Properties getTableProperties(String schemaName, String tableName) throws SQLException { return PropertyInfo.getConglomerateProperties( schemaName, tableName, false ); } /** * Get the Properties associated with a given index. * * @param schemaName The name of the schema that the index is in. * @param indexName The name of the index. * * @return Properties The Properties associated with the specified index. * (An empty Properties is returned if the index does not exist.) * @exception SQLException on error */ public static Properties getIndexProperties(String schemaName, String indexName) throws SQLException { return PropertyInfo.getConglomerateProperties( schemaName, indexName, true ); } /** Set or delete the value of a property of the database on the current connection. @param key the property key @param value the new value, if null the property is deleted. @exception SQLException on error */ public static void setDatabaseProperty(String key, String value) throws SQLException { LanguageConnectionContext lcc = ConnectionUtil.getCurrentLCC(); try { Authorizer a = lcc.getAuthorizer(); a.authorize((Activation) null, Authorizer.PROPERTY_WRITE_OP); // Get the current transaction controller TransactionController tc = lcc.getTransactionExecute(); tc.setProperty(key, value, false); } catch (StandardException se) { throw PublicAPI.wrapStandardException(se); } } /** Internal use only. */ private PropertyInfo() {} ////////////////////////////////////////////////////////////////////////////// // // PRIVATE METHODS // ///////////////////////////////////////////////////////////////////////////// /** * Get the Properties associated with a given conglomerate * * @param schemaName The name of the schema that the conglomerate is in. * @param conglomerateName The name of the conglomerate. * * @return Properties The Properties associated with the specified conglomerate. * (An empty Properties is returned if the conglomerate does not exist.) * @exception SQLException on error */ private static Properties getConglomerateProperties( String schemaName, String conglomerateName, boolean isIndex ) throws SQLException { long conglomerateNumber; // find the language context. LanguageConnectionContext lcc = ConnectionUtil.getCurrentLCC(); // Get the current transaction controller TransactionController tc = lcc.getTransactionExecute(); try { // find the DataDictionary DataDictionary dd = lcc.getDataDictionary(); // get the SchemaDescriptor SchemaDescriptor sd = dd.getSchemaDescriptor(schemaName, tc, true); if ( !isIndex) { // get the TableDescriptor for the table TableDescriptor td = dd.getTableDescriptor(conglomerateName, sd, tc); // Return an empty Properties if table does not exist or if it is for a view. if ((td == null) || td.getTableType() == TableDescriptor.VIEW_TYPE) { return new Properties(); } conglomerateNumber = td.getHeapConglomerateId(); } else { // get the ConglomerateDescriptor for the index ConglomerateDescriptor cd = dd.getConglomerateDescriptor(conglomerateName, sd, false); // Return an empty Properties if index does not exist if (cd == null) { return new Properties(); } conglomerateNumber = cd.getConglomerateNumber(); } ConglomerateController cc = tc.openConglomerate( conglomerateNumber, false, 0, TransactionController.MODE_RECORD, TransactionController.ISOLATION_SERIALIZABLE); Properties properties = tc.getUserCreateConglomPropList(); cc.getTableProperties( properties ); cc.close(); return properties; } catch (StandardException se) { throw PublicAPI.wrapStandardException(se); } } }
DERBY-6264: Improve test coverage of org.apache.derby.iapi.db.PropertyInfo This patch was contributed by Ahsan Shamsudeen (ahsan dot competition at gmail dot com) This patch removes several unused methods from the PropertyInfo class. These classes were part of the original Cloudscape SQL-J language many years ago, but are not used in Derby. Removing the unused methods simplifies the class. Should we ever decide to revive the features of the SQL-J language, we can recover these methods from the older versions of the class in Subversion. git-svn-id: 2c06e9c5008124d912b69f0b82df29d4867c0ce2@1497205 13f79535-47bb-0310-9956-ffa450edef68
java/engine/org/apache/derby/iapi/db/PropertyInfo.java
DERBY-6264: Improve test coverage of org.apache.derby.iapi.db.PropertyInfo
Java
apache-2.0
1794eacd05783caf579a328e6b9c1aa3da1c90c0
0
lorenamgUMU/sakai,liubo404/sakai,whumph/sakai,duke-compsci290-spring2016/sakai,frasese/sakai,pushyamig/sakai,surya-janani/sakai,rodriguezdevera/sakai,duke-compsci290-spring2016/sakai,buckett/sakai-gitflow,lorenamgUMU/sakai,frasese/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,udayg/sakai,kingmook/sakai,Fudan-University/sakai,udayg/sakai,wfuedu/sakai,lorenamgUMU/sakai,frasese/sakai,bzhouduke123/sakai,udayg/sakai,clhedrick/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,kwedoff1/sakai,willkara/sakai,ouit0408/sakai,noondaysun/sakai,bzhouduke123/sakai,puramshetty/sakai,kingmook/sakai,kwedoff1/sakai,whumph/sakai,Fudan-University/sakai,joserabal/sakai,puramshetty/sakai,clhedrick/sakai,kingmook/sakai,noondaysun/sakai,buckett/sakai-gitflow,wfuedu/sakai,ktakacs/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,duke-compsci290-spring2016/sakai,liubo404/sakai,zqian/sakai,puramshetty/sakai,udayg/sakai,introp-software/sakai,zqian/sakai,bzhouduke123/sakai,joserabal/sakai,lorenamgUMU/sakai,bkirschn/sakai,frasese/sakai,willkara/sakai,hackbuteer59/sakai,whumph/sakai,joserabal/sakai,ktakacs/sakai,lorenamgUMU/sakai,wfuedu/sakai,frasese/sakai,puramshetty/sakai,pushyamig/sakai,buckett/sakai-gitflow,tl-its-umich-edu/sakai,bzhouduke123/sakai,wfuedu/sakai,ktakacs/sakai,conder/sakai,noondaysun/sakai,buckett/sakai-gitflow,ouit0408/sakai,colczr/sakai,willkara/sakai,colczr/sakai,whumph/sakai,introp-software/sakai,whumph/sakai,OpenCollabZA/sakai,tl-its-umich-edu/sakai,buckett/sakai-gitflow,zqian/sakai,wfuedu/sakai,kwedoff1/sakai,bzhouduke123/sakai,colczr/sakai,duke-compsci290-spring2016/sakai,tl-its-umich-edu/sakai,kingmook/sakai,colczr/sakai,surya-janani/sakai,Fudan-University/sakai,liubo404/sakai,rodriguezdevera/sakai,duke-compsci290-spring2016/sakai,OpenCollabZA/sakai,zqian/sakai,conder/sakai,wfuedu/sakai,liubo404/sakai,pushyamig/sakai,rodriguezdevera/sakai,pushyamig/sakai,ouit0408/sakai,joserabal/sakai,surya-janani/sakai,zqian/sakai,bkirschn/sakai,kwedoff1/sakai,introp-software/sakai,ktakacs/sakai,conder/sakai,ouit0408/sakai,surya-janani/sakai,surya-janani/sakai,bkirschn/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,conder/sakai,rodriguezdevera/sakai,ktakacs/sakai,introp-software/sakai,introp-software/sakai,OpenCollabZA/sakai,ktakacs/sakai,joserabal/sakai,ouit0408/sakai,kingmook/sakai,OpenCollabZA/sakai,pushyamig/sakai,kwedoff1/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,kingmook/sakai,conder/sakai,pushyamig/sakai,rodriguezdevera/sakai,frasese/sakai,surya-janani/sakai,willkara/sakai,colczr/sakai,ktakacs/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,joserabal/sakai,puramshetty/sakai,hackbuteer59/sakai,noondaysun/sakai,surya-janani/sakai,udayg/sakai,whumph/sakai,ouit0408/sakai,rodriguezdevera/sakai,hackbuteer59/sakai,Fudan-University/sakai,conder/sakai,wfuedu/sakai,liubo404/sakai,OpenCollabZA/sakai,bzhouduke123/sakai,whumph/sakai,whumph/sakai,colczr/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,OpenCollabZA/sakai,hackbuteer59/sakai,rodriguezdevera/sakai,introp-software/sakai,kwedoff1/sakai,noondaysun/sakai,conder/sakai,kwedoff1/sakai,bzhouduke123/sakai,bkirschn/sakai,lorenamgUMU/sakai,conder/sakai,ouit0408/sakai,liubo404/sakai,frasese/sakai,zqian/sakai,introp-software/sakai,surya-janani/sakai,liubo404/sakai,colczr/sakai,pushyamig/sakai,OpenCollabZA/sakai,clhedrick/sakai,kingmook/sakai,udayg/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,lorenamgUMU/sakai,udayg/sakai,hackbuteer59/sakai,kwedoff1/sakai,noondaysun/sakai,puramshetty/sakai,kingmook/sakai,pushyamig/sakai,Fudan-University/sakai,lorenamgUMU/sakai,zqian/sakai,bkirschn/sakai,joserabal/sakai,willkara/sakai,bkirschn/sakai,Fudan-University/sakai,bkirschn/sakai,Fudan-University/sakai,tl-its-umich-edu/sakai,udayg/sakai,colczr/sakai,ktakacs/sakai,willkara/sakai,clhedrick/sakai,joserabal/sakai,bzhouduke123/sakai,hackbuteer59/sakai,liubo404/sakai,rodriguezdevera/sakai,wfuedu/sakai,puramshetty/sakai,zqian/sakai,clhedrick/sakai,bkirschn/sakai,clhedrick/sakai,ouit0408/sakai,willkara/sakai,frasese/sakai,Fudan-University/sakai,OpenCollabZA/sakai
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.assignment.tool; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Hashtable; import java.util.HashSet; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.nio.channels.*; import java.nio.*; import org.sakaiproject.announcement.api.AnnouncementChannel; import org.sakaiproject.announcement.api.AnnouncementMessage; import org.sakaiproject.announcement.api.AnnouncementMessageEdit; import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit; import org.sakaiproject.announcement.api.AnnouncementService; import org.sakaiproject.assignment.api.Assignment; import org.sakaiproject.assignment.api.AssignmentContentEdit; import org.sakaiproject.assignment.api.AssignmentEdit; import org.sakaiproject.assignment.api.AssignmentSubmission; import org.sakaiproject.assignment.api.AssignmentSubmissionEdit; import org.sakaiproject.assignment.cover.AssignmentService; import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer; import org.sakaiproject.assignment.taggable.api.TaggingHelperInfo; import org.sakaiproject.assignment.taggable.api.TaggingManager; import org.sakaiproject.assignment.taggable.api.TaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Pager; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Sort; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.calendar.api.Calendar; import org.sakaiproject.calendar.api.CalendarEvent; import org.sakaiproject.calendar.api.CalendarEventEdit; import org.sakaiproject.calendar.api.CalendarService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.PagedResourceActionII; import org.sakaiproject.cheftool.PortletConfig; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.ContentResourceEdit; import org.sakaiproject.content.api.ContentTypeImageService; import org.sakaiproject.content.api.FilePickerHelper; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentResourceEdit; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.event.cover.NotificationService; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.InUseException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException; import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException; import org.sakaiproject.service.gradebook.shared.ConflictingExternalIdException; import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.FileItem; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.SortedIterator; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; import org.sakaiproject.contentreview.service.ContentReviewService; /** * <p> * AssignmentAction is the action class for the assignment tool. * </p> */ public class AssignmentAction extends PagedResourceActionII { private static ResourceLoader rb = new ResourceLoader("assignment"); private static final String ASSIGNMENT_TOOL_ID = "sakai.assignment.grades"; private static final Boolean allowReviewService = ServerConfigurationService.getBoolean("assignment.useContentReview", false); /** Is the review service available? */ private static final String ALLOW_REVIEW_SERVICE = "allow_review_service"; private static final String NEW_ASSIGNMENT_USE_REVIEW_SERVICE = "new_assignment_use_review_service"; private static final String NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW = "new_assignment_allow_student_view"; /** The attachments */ private static final String ATTACHMENTS = "Assignment.attachments"; /** The content type image lookup service in the State. */ private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "Assignment.content_type_image_service"; /** The calendar service in the State. */ private static final String STATE_CALENDAR_SERVICE = "Assignment.calendar_service"; /** The announcement service in the State. */ private static final String STATE_ANNOUNCEMENT_SERVICE = "Assignment.announcement_service"; /** The calendar object */ private static final String CALENDAR = "calendar"; /** The calendar tool */ private static final String CALENDAR_TOOL_EXIST = "calendar_tool_exisit"; /** The announcement tool */ private static final String ANNOUNCEMENT_TOOL_EXIST = "announcement_tool_exist"; /** The announcement channel */ private static final String ANNOUNCEMENT_CHANNEL = "announcement_channel"; /** The state mode */ private static final String STATE_MODE = "Assignment.mode"; /** The context string */ private static final String STATE_CONTEXT_STRING = "Assignment.context_string"; /** The user */ private static final String STATE_USER = "Assignment.user"; // SECTION MOD /** Used to keep track of the section info not currently being used. */ private static final String STATE_SECTION_STRING = "Assignment.section_string"; /** **************************** sort assignment ********************** */ /** state sort * */ private static final String SORTED_BY = "Assignment.sorted_by"; /** state sort ascendingly * */ private static final String SORTED_ASC = "Assignment.sorted_asc"; /** default sorting */ private static final String SORTED_BY_DEFAULT = "default"; /** sort by assignment title */ private static final String SORTED_BY_TITLE = "title"; /** sort by assignment section */ private static final String SORTED_BY_SECTION = "section"; /** sort by assignment due date */ private static final String SORTED_BY_DUEDATE = "duedate"; /** sort by assignment open date */ private static final String SORTED_BY_OPENDATE = "opendate"; /** sort by assignment status */ private static final String SORTED_BY_ASSIGNMENT_STATUS = "assignment_status"; /** sort by assignment submission status */ private static final String SORTED_BY_SUBMISSION_STATUS = "submission_status"; /** sort by assignment number of submissions */ private static final String SORTED_BY_NUM_SUBMISSIONS = "num_submissions"; /** sort by assignment number of ungraded submissions */ private static final String SORTED_BY_NUM_UNGRADED = "num_ungraded"; /** sort by assignment submission grade */ private static final String SORTED_BY_GRADE = "grade"; /** sort by assignment maximun grade available */ private static final String SORTED_BY_MAX_GRADE = "max_grade"; /** sort by assignment range */ private static final String SORTED_BY_FOR = "for"; /** sort by group title */ private static final String SORTED_BY_GROUP_TITLE = "group_title"; /** sort by group description */ private static final String SORTED_BY_GROUP_DESCRIPTION = "group_description"; /** *************************** sort submission in instructor grade view *********************** */ /** state sort submission* */ private static final String SORTED_GRADE_SUBMISSION_BY = "Assignment.grade_submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_GRADE_SUBMISSION_ASC = "Assignment.grade_submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_GRADE_SUBMISSION_BY_LASTNAME = "sorted_grade_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME = "sorted_grade_submission_by_submit_time"; /** state sort submission by submission status * */ private static final String SORTED_GRADE_SUBMISSION_BY_STATUS = "sorted_grade_submission_by_status"; /** state sort submission by submission grade * */ private static final String SORTED_GRADE_SUBMISSION_BY_GRADE = "sorted_grade_submission_by_grade"; /** state sort submission by submission released * */ private static final String SORTED_GRADE_SUBMISSION_BY_RELEASED = "sorted_grade_submission_by_released"; /** state sort submissuib by content review score **/ private static final String SORTED_GRADE_SUBMISSION_CONTENTREVIEW = "sorted_grade_submission_by_contentreview"; /** *************************** sort submission *********************** */ /** state sort submission* */ private static final String SORTED_SUBMISSION_BY = "Assignment.submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_SUBMISSION_ASC = "Assignment.submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_SUBMISSION_BY_LASTNAME = "sorted_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_SUBMISSION_BY_SUBMIT_TIME = "sorted_submission_by_submit_time"; /** state sort submission by submission grade * */ private static final String SORTED_SUBMISSION_BY_GRADE = "sorted_submission_by_grade"; /** state sort submission by submission status * */ private static final String SORTED_SUBMISSION_BY_STATUS = "sorted_submission_by_status"; /** state sort submission by submission released * */ private static final String SORTED_SUBMISSION_BY_RELEASED = "sorted_submission_by_released"; /** state sort submission by assignment title */ private static final String SORTED_SUBMISSION_BY_ASSIGNMENT = "sorted_submission_by_assignment"; /** state sort submission by max grade */ private static final String SORTED_SUBMISSION_BY_MAX_GRADE = "sorted_submission_by_max_grade"; /*********************** Sort by user sort name *****************************************/ private static final String SORTED_USER_BY_SORTNAME = "sorted_user_by_sortname"; /** ******************** student's view assignment submission ****************************** */ /** the assignment object been viewing * */ private static final String VIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "Assignment.view_submission_assignment_reference"; /** the submission text to the assignment * */ private static final String VIEW_SUBMISSION_TEXT = "Assignment.view_submission_text"; /** the submission answer to Honor Pledge * */ private static final String VIEW_SUBMISSION_HONOR_PLEDGE_YES = "Assignment.view_submission_honor_pledge_yes"; /** ***************** student's preview of submission *************************** */ /** the assignment id * */ private static final String PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "preview_submission_assignment_reference"; /** the submission text * */ private static final String PREVIEW_SUBMISSION_TEXT = "preview_submission_text"; /** the submission honor pledge answer * */ private static final String PREVIEW_SUBMISSION_HONOR_PLEDGE_YES = "preview_submission_honor_pledge_yes"; /** the submission attachments * */ private static final String PREVIEW_SUBMISSION_ATTACHMENTS = "preview_attachments"; /** the flag indicate whether the to show the student view or not */ private static final String PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG = "preview_assignment_student_view_hide_flag"; /** the flag indicate whether the to show the assignment info or not */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG = "preview_assignment_assignment_hide_flag"; /** the assignment id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_ID = "preview_assignment_assignment_id"; /** the assignment content id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID = "preview_assignment_assignmentcontent_id"; /** ************** view assignment ***************************************** */ /** the hide assignment flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG = "view_assignment_hide_assignment_flag"; /** the hide student view flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG = "view_assignment_hide_student_view_flag"; /** ******************* instructor's view assignment ***************************** */ private static final String VIEW_ASSIGNMENT_ID = "view_assignment_id"; /** ******************* instructor's edit assignment ***************************** */ private static final String EDIT_ASSIGNMENT_ID = "edit_assignment_id"; /** ******************* instructor's delete assignment ids ***************************** */ private static final String DELETE_ASSIGNMENT_IDS = "delete_assignment_ids"; /** ******************* flags controls the grade assignment page layout ******************* */ private static final String GRADE_ASSIGNMENT_EXPAND_FLAG = "grade_assignment_expand_flag"; private static final String GRADE_SUBMISSION_EXPAND_FLAG = "grade_submission_expand_flag"; private static final String GRADE_NO_SUBMISSION_DEFAULT_GRADE = "grade_no_submission_default_grade"; /** ******************* instructor's grade submission ***************************** */ private static final String GRADE_SUBMISSION_ASSIGNMENT_ID = "grade_submission_assignment_id"; private static final String GRADE_SUBMISSION_SUBMISSION_ID = "grade_submission_submission_id"; private static final String GRADE_SUBMISSION_FEEDBACK_COMMENT = "grade_submission_feedback_comment"; private static final String GRADE_SUBMISSION_FEEDBACK_TEXT = "grade_submission_feedback_text"; private static final String GRADE_SUBMISSION_FEEDBACK_ATTACHMENT = "grade_submission_feedback_attachment"; private static final String GRADE_SUBMISSION_GRADE = "grade_submission_grade"; private static final String GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG = "grade_submission_assignment_expand_flag"; private static final String GRADE_SUBMISSION_ALLOW_RESUBMIT = "grade_submission_allow_resubmit"; /** ******************* instructor's export assignment ***************************** */ private static final String EXPORT_ASSIGNMENT_REF = "export_assignment_ref"; /** * Is review service enabled? */ private static final String ENABLE_REVIEW_SERVICE = "enable_review_service"; private static final String EXPORT_ASSIGNMENT_ID = "export_assignment_id"; /** ****************** instructor's new assignment ****************************** */ private static final String NEW_ASSIGNMENT_TITLE = "new_assignment_title"; // assignment order for default view private static final String NEW_ASSIGNMENT_ORDER = "new_assignment_order"; // open date private static final String NEW_ASSIGNMENT_OPENMONTH = "new_assignment_openmonth"; private static final String NEW_ASSIGNMENT_OPENDAY = "new_assignment_openday"; private static final String NEW_ASSIGNMENT_OPENYEAR = "new_assignment_openyear"; private static final String NEW_ASSIGNMENT_OPENHOUR = "new_assignment_openhour"; private static final String NEW_ASSIGNMENT_OPENMIN = "new_assignment_openmin"; private static final String NEW_ASSIGNMENT_OPENAMPM = "new_assignment_openampm"; // due date private static final String NEW_ASSIGNMENT_DUEMONTH = "new_assignment_duemonth"; private static final String NEW_ASSIGNMENT_DUEDAY = "new_assignment_dueday"; private static final String NEW_ASSIGNMENT_DUEYEAR = "new_assignment_dueyear"; private static final String NEW_ASSIGNMENT_DUEHOUR = "new_assignment_duehour"; private static final String NEW_ASSIGNMENT_DUEMIN = "new_assignment_duemin"; private static final String NEW_ASSIGNMENT_DUEAMPM = "new_assignment_dueampm"; private static final String NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID = "new_assignment_duedate_calendar_assignment_id"; private static final String NEW_ASSIGNMENT_PAST_DUE_DATE = "new_assignment_past_due_date"; // close date private static final String NEW_ASSIGNMENT_ENABLECLOSEDATE = "new_assignment_enableclosedate"; private static final String NEW_ASSIGNMENT_CLOSEMONTH = "new_assignment_closemonth"; private static final String NEW_ASSIGNMENT_CLOSEDAY = "new_assignment_closeday"; private static final String NEW_ASSIGNMENT_CLOSEYEAR = "new_assignment_closeyear"; private static final String NEW_ASSIGNMENT_CLOSEHOUR = "new_assignment_closehour"; private static final String NEW_ASSIGNMENT_CLOSEMIN = "new_assignment_closemin"; private static final String NEW_ASSIGNMENT_CLOSEAMPM = "new_assignment_closeampm"; private static final String NEW_ASSIGNMENT_ATTACHMENT = "new_assignment_attachment"; private static final String NEW_ASSIGNMENT_SECTION = "new_assignment_section"; private static final String NEW_ASSIGNMENT_SUBMISSION_TYPE = "new_assignment_submission_type"; private static final String NEW_ASSIGNMENT_GRADE_TYPE = "new_assignment_grade_type"; private static final String NEW_ASSIGNMENT_GRADE_POINTS = "new_assignment_grade_points"; private static final String NEW_ASSIGNMENT_DESCRIPTION = "new_assignment_instructions"; private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled"; private static final String NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED = "new_assignment_open_date_announced"; private static final String NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE = "new_assignment_check_add_honor_pledge"; private static final String NEW_ASSIGNMENT_HIDE_OPTION_FLAG = "new_assignment_hide_option_flag"; private static final String NEW_ASSIGNMENT_FOCUS = "new_assignment_focus"; private static final String NEW_ASSIGNMENT_DESCRIPTION_EMPTY = "new_assignment_description_empty"; private static final String NEW_ASSIGNMENT_ADD_TO_GRADEBOOK = "new_assignment_add_to_gradebook"; private static final String NEW_ASSIGNMENT_RANGE = "new_assignment_range"; private static final String NEW_ASSIGNMENT_GROUPS = "new_assignment_groups"; private static final String NEW_ASSIGNMENT_PAST_CLOSE_DATE = "new_assignment_past_close_date"; /**************************** assignment year range *************************/ private static final String NEW_ASSIGNMENT_YEAR_RANGE_FROM = "new_assignment_year_range_from"; private static final String NEW_ASSIGNMENT_YEAR_RANGE_TO = "new_assignment_year_range_to"; // submission level of resubmit due time private static final String ALLOW_RESUBMIT_CLOSEMONTH = "allow_resubmit_closeMonth"; private static final String ALLOW_RESUBMIT_CLOSEDAY = "allow_resubmit_closeDay"; private static final String ALLOW_RESUBMIT_CLOSEYEAR = "allow_resubmit_closeYear"; private static final String ALLOW_RESUBMIT_CLOSEHOUR = "allow_resubmit_closeHour"; private static final String ALLOW_RESUBMIT_CLOSEMIN = "allow_resubmit_closeMin"; private static final String ALLOW_RESUBMIT_CLOSEAMPM = "allow_resubmit_closeAMPM"; private static final String ATTACHMENTS_MODIFIED = "attachments_modified"; /** **************************** instructor's view student submission ***************** */ // the show/hide table based on member id private static final String STUDENT_LIST_SHOW_TABLE = "STUDENT_LIST_SHOW_TABLE"; /** **************************** student view grade submission id *********** */ private static final String VIEW_GRADE_SUBMISSION_ID = "view_grade_submission_id"; // alert for grade exceeds max grade setting private static final String GRADE_GREATER_THAN_MAX_ALERT = "grade_greater_than_max_alert"; /** **************************** modes *************************** */ /** The list view of assignments */ private static final String MODE_LIST_ASSIGNMENTS = "lisofass1"; // set in velocity template /** The student view of an assignment submission */ private static final String MODE_STUDENT_VIEW_SUBMISSION = "Assignment.mode_view_submission"; /** The student view of an assignment submission confirmation */ private static final String MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "Assignment.mode_view_submission_confirmation"; /** The student preview of an assignment submission */ private static final String MODE_STUDENT_PREVIEW_SUBMISSION = "Assignment.mode_student_preview_submission"; /** The student view of graded submission */ private static final String MODE_STUDENT_VIEW_GRADE = "Assignment.mode_student_view_grade"; /** The student view of assignments */ private static final String MODE_STUDENT_VIEW_ASSIGNMENT = "Assignment.mode_student_view_assignment"; /** The instructor view of creating a new assignment or editing an existing one */ private static final String MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "Assignment.mode_instructor_new_edit_assignment"; /** The instructor view to reorder assignments */ private static final String MODE_INSTRUCTOR_REORDER_ASSIGNMENT = "reorder"; /** The instructor view to delete an assignment */ private static final String MODE_INSTRUCTOR_DELETE_ASSIGNMENT = "Assignment.mode_instructor_delete_assignment"; /** The instructor view to grade an assignment */ private static final String MODE_INSTRUCTOR_GRADE_ASSIGNMENT = "Assignment.mode_instructor_grade_assignment"; /** The instructor view to grade a submission */ private static final String MODE_INSTRUCTOR_GRADE_SUBMISSION = "Assignment.mode_instructor_grade_submission"; /** The instructor view of preview grading a submission */ private static final String MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "Assignment.mode_instructor_preview_grade_submission"; /** The instructor preview of one assignment */ private static final String MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "Assignment.mode_instructor_preview_assignments"; /** The instructor view of one assignment */ private static final String MODE_INSTRUCTOR_VIEW_ASSIGNMENT = "Assignment.mode_instructor_view_assignments"; /** The instructor view to list students of an assignment */ private static final String MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "lisofass2"; // set in velocity template /** The instructor view of assignment submission report */ private static final String MODE_INSTRUCTOR_REPORT_SUBMISSIONS = "grarep"; // set in velocity template /** The instructor view of uploading all from archive file */ private static final String MODE_INSTRUCTOR_UPLOAD_ALL = "uploadAll"; /** The student view of assignment submission report */ private static final String MODE_STUDENT_VIEW = "stuvie"; // set in velocity template /** ************************* vm names ************************** */ /** The list view of assignments */ private static final String TEMPLATE_LIST_ASSIGNMENTS = "_list_assignments"; /** The student view of assignment */ private static final String TEMPLATE_STUDENT_VIEW_ASSIGNMENT = "_student_view_assignment"; /** The student view of showing an assignment submission */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION = "_student_view_submission"; /** The student view of an assignment submission confirmation */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "_student_view_submission_confirmation"; /** The student preview an assignment submission */ private static final String TEMPLATE_STUDENT_PREVIEW_SUBMISSION = "_student_preview_submission"; /** The student view of graded submission */ private static final String TEMPLATE_STUDENT_VIEW_GRADE = "_student_view_grade"; /** The instructor view to create a new assignment or edit an existing one */ private static final String TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "_instructor_new_edit_assignment"; /** The instructor view to reorder the default assignments */ private static final String TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT = "_instructor_reorder_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT = "_instructor_delete_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION = "_instructor_grading_submission"; /** The instructor preview to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "_instructor_preview_grading_submission"; /** The instructor view to grade the assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT = "_instructor_list_submissions"; /** The instructor preview of assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "_instructor_preview_assignment"; /** The instructor view of assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT = "_instructor_view_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "_instructor_student_list_submissions"; /** The instructor view to assignment submission report */ private static final String TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS = "_instructor_report_submissions"; /** The instructor view to upload all information from archive file */ private static final String TEMPLATE_INSTRUCTOR_UPLOAD_ALL = "_instructor_uploadAll"; /** The opening mark comment */ private static final String COMMENT_OPEN = "{{"; /** The closing mark for comment */ private static final String COMMENT_CLOSE = "}}"; /** The selected view */ private static final String STATE_SELECTED_VIEW = "state_selected_view"; /** The configuration choice of with grading option or not */ private static final String WITH_GRADES = "with_grades"; /** The alert flag when doing global navigation from improper mode */ private static final String ALERT_GLOBAL_NAVIGATION = "alert_global_navigation"; /** The total list item before paging */ private static final String STATE_PAGEING_TOTAL_ITEMS = "state_paging_total_items"; /** is current user allowed to grade assignment? */ private static final String STATE_ALLOW_GRADE_SUBMISSION = "state_allow_grade_submission"; /** property for previous feedback attachments **/ private static final String PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS = "prop_submission_previous_feedback_attachments"; /** the user and submission list for list of submissions page */ private static final String USER_SUBMISSIONS = "user_submissions"; /** ************************* Taggable constants ************************** */ /** identifier of tagging provider that will provide the appropriate helper */ private static final String PROVIDER_ID = "providerId"; /** Reference to an activity */ private static final String ACTIVITY_REF = "activityRef"; /** Reference to an item */ private static final String ITEM_REF = "itemRef"; /** session attribute for list of decorated tagging providers */ private static final String PROVIDER_LIST = "providerList"; // whether the choice of emails instructor submission notification is available in the installation private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS = "assignment.instructor.notifications"; // default for whether or how the instructor receive submission notification emails, none(default)|each|digest private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT = "assignment.instructor.notifications.default"; /****************************** Upload all screen ***************************/ private static final String UPLOAD_ALL_HAS_SUBMISSION_TEXT = "upload_all_has_submission_text"; private static final String UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT = "upload_all_has_submission_attachment"; private static final String UPLOAD_ALL_HAS_GRADEFILE = "upload_all_has_gradefile"; private static final String UPLOAD_ALL_HAS_COMMENTS= "upload_all_has_comments"; private static final String UPLOAD_ALL_HAS_FEEDBACK_TEXT= "upload_all_has_feedback_text"; private static final String UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT = "upload_all_has_feedback_attachment"; private static final String UPLOAD_ALL_RELEASE_GRADES = "upload_all_release_grades"; // this is to track whether the site has multiple assignment, hence if true, show the reorder link private static final String HAS_MULTIPLE_ASSIGNMENTS = "has_multiple_assignments"; // view all or grouped submission list private static final String VIEW_SUBMISSION_LIST_OPTION = "view_submission_list_option"; private ContentHostingService m_contentHostingService = null; /** * central place for dispatching the build routines based on the state name */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String template = null; context.put("tlang", rb); context.put("cheffeedbackhelper", this); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // allow add assignment? boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); context.put("allowAddAssignment", Boolean.valueOf(allowAddAssignment)); Object allowGradeSubmission = state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION); // allow update site? context.put("allowUpdateSite", Boolean .valueOf(SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING)))); // allow all.groups? boolean allowAllGroups = AssignmentService.allowAllGroups(contextString); context.put("allowAllGroups", Boolean.valueOf(allowAllGroups)); //Is the review service allowed? Site s = null; try { s = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (IdUnusedException iue) { Log.warn("chef", "Site not found!"); } getContentReviewService(); if (allowReviewService && contentReviewService.isSiteAcceptable(s)) { context.put("allowReviewService", allowReviewService); } else { context.put("allowReviewService", false); } // grading option context.put("withGrade", state.getAttribute(WITH_GRADES)); // the grade type table context.put("gradeTypeTable", gradeTypeTable()); String mode = (String) state.getAttribute(STATE_MODE); if (!mode.equals(MODE_LIST_ASSIGNMENTS)) { // allow grade assignment? if (state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION) == null) { state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.FALSE); } context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); } if (mode.equals(MODE_LIST_ASSIGNMENTS)) { // build the context for the student assignment view template = build_list_assignments_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_ASSIGNMENT)) { // the student view of assignment template = build_student_view_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one assignment submission template = build_student_view_submission_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION)) { // build the context for showing one assignment submission confirmation template = build_student_view_submission_confirmation_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION)) { // build the context for showing one assignment submission template = build_student_preview_submission_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_GRADE)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one graded submission template = build_student_view_grade_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { // allow add assignment? boolean allowAddSiteAssignment = AssignmentService.allowAddSiteAssignment(contextString); context.put("allowAddSiteAssignment", Boolean.valueOf(allowAddSiteAssignment)); // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_new_edit_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT)) { if (state.getAttribute(DELETE_ASSIGNMENT_IDS) != null) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's delete assignment template = build_instructor_delete_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_GRADE_ASSIGNMENT)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's grade assignment template = build_instructor_grade_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's grade submission template = build_instructor_grade_submission_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's preview grade submission template = build_instructor_preview_grade_submission_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)) { // build the context for preview one assignment template = build_instructor_preview_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for view one assignment template = build_instructor_view_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's create new assignment view template = build_instructor_view_students_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of report submissions template = build_instructor_report_submissions(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_UPLOAD_ALL)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of uploading all info from archive file template = build_instructor_upload_all(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_REORDER_ASSIGNMENT)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_reorder_assignment_context(portlet, context, data, state); } if (template == null) { // default to student list view state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); template = build_list_assignments_context(portlet, context, data, state); } // this is a check for seeing if there are any assignments. The check is used to see if we display a Reorder link in the vm files if (state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS) != null) { context.put("assignmentscheck", state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS)); } return template; } // buildNormalContext /** * build the student view of showing an assignment submission */ protected String build_student_view_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); User user = (User) state.getAttribute(STATE_USER); String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment assignment = null; try { assignment = AssignmentService.getAssignment(currentAssignmentReference); context.put("assignment", assignment); context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit(contextString, assignment))); if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { context.put("nonElectronicType", Boolean.TRUE); } AssignmentSubmission s = AssignmentService.getSubmission(assignment.getReference(), user); if (s != null) { context.put("submission", s); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } // name value pairs for the vm context.put("name_submission_text", VIEW_SUBMISSION_TEXT); context.put("value_submission_text", state.getAttribute(VIEW_SUBMISSION_TEXT)); context.put("name_submission_honor_pledge_yes", VIEW_SUBMISSION_HONOR_PLEDGE_YES); context.put("value_submission_honor_pledge_yes", state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("currentTime", TimeService.newTime()); boolean allowSubmit = AssignmentService.allowAddSubmission((String) state.getAttribute(STATE_CONTEXT_STRING)); if (!allowSubmit) { addAlert(state, rb.getString("not_allowed_to_submit")); } context.put("allowSubmit", new Boolean(allowSubmit)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION; } // build_student_view_submission_context /** * build the student view of showing an assignment submission confirmation */ protected String build_student_view_submission_confirmation_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); // get user information User user = (User) state.getAttribute(STATE_USER); context.put("user_name", user.getDisplayName()); context.put("user_id", user.getDisplayId()); if (StringUtil.trimToNull(user.getEmail()) != null) context.put("user_email", user.getEmail()); // get site information try { // get current site Site site = SiteService.getSite(contextString); context.put("site_title", site.getTitle()); } catch (Exception ignore) { Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString); } // get assignment and submission information String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { Assignment currentAssignment = AssignmentService.getAssignment(currentAssignmentReference); context.put("assignment_title", currentAssignment.getTitle()); AssignmentSubmission s = AssignmentService.getSubmission(currentAssignment.getReference(), user); if (s != null) { context.put("submitted", Boolean.valueOf(s.getSubmitted())); context.put("submission_id", s.getId()); if (s.getTimeSubmitted() != null) { context.put("submit_time", s.getTimeSubmitted().toStringLocalFull()); } List attachments = s.getSubmittedAttachments(); if (attachments != null && attachments.size()>0) { context.put("submit_attachments", s.getSubmittedAttachments()); } context.put("submit_text", StringUtil.trimToNull(s.getSubmittedText())); context.put("email_confirmation", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.submission.confirmation.email", true))); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION; } // build_student_view_submission_confirmation_context /** * build the student view of assignment */ protected String build_student_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); String aId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); Assignment assignment = null; try { assignment = AssignmentService.getAssignment(aId); context.put("assignment", assignment); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_ASSIGNMENT; } // build_student_view_submission_context /** * build the student preview of showing an assignment submission */ protected String build_student_preview_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { User user = (User) state.getAttribute(STATE_USER); String aReference = (String) state.getAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { context.put("assignment", AssignmentService.getAssignment(aReference)); context.put("submission", AssignmentService.getSubmission(aReference, user)); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } context.put("text", state.getAttribute(PREVIEW_SUBMISSION_TEXT)); context.put("honor_pledge_yes", state.getAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("attachments", state.getAttribute(PREVIEW_SUBMISSION_ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_PREVIEW_SUBMISSION; } // build_student_preview_submission_context /** * build the student view of showing a graded submission */ protected String build_student_view_grade_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); AssignmentSubmission submission = null; try { submission = AssignmentService.getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID)); Assignment assignment = submission.getAssignment(); context.put("assignment", assignment); if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { context.put("nonElectronicType", Boolean.TRUE); } context.put("submission", submission); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_get_submission")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && submission != null) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> itemHelpers = new ArrayList<TaggingHelperInfo>(); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getItemHelperInfo( assignmentActivityProducer.getItem( submission, UserDirectoryService.getCurrentUser() .getId()).getReference()); if (helper != null) { itemHelpers.add(helper); } } addItem(context, submission, UserDirectoryService.getCurrentUser().getId()); addActivity(context, submission.getAssignment()); context.put("itemHelpers", itemHelpers); context.put("taggable", Boolean.valueOf(true)); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_GRADE; } // build_student_view_grade_context /** * build the view of assignments list */ protected String build_list_assignments_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); context.put("providers", taggingManager.getProviders()); context.put("taggable", Boolean.valueOf(true)); } String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("contextString", contextString); context.put("user", state.getAttribute(STATE_USER)); context.put("service", AssignmentService.getInstance()); context.put("TimeService", TimeService.getInstance()); context.put("LongObject", new Long(TimeService.newTime().getTime())); context.put("currentTime", TimeService.newTime()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); // clean sort criteria if (sortedBy.equals(SORTED_BY_GROUP_TITLE) || sortedBy.equals(SORTED_BY_GROUP_DESCRIPTION)) { sortedBy = SORTED_BY_DUEDATE; sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sortedBy); state.setAttribute(SORTED_ASC, sortedAsc); } context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); if (state.getAttribute(STATE_SELECTED_VIEW) != null) { context.put("view", state.getAttribute(STATE_SELECTED_VIEW)); } Hashtable assignments_submissions = new Hashtable(); List assignments = prepPage(state); context.put("assignments", assignments.iterator()); // allow get assignment context.put("allowGetAssignment", Boolean.valueOf(AssignmentService.allowGetAssignment(contextString))); // test whether user user can grade at least one assignment // and update the state variable. boolean allowGradeSubmission = false; for (Iterator aIterator=assignments.iterator(); !allowGradeSubmission && aIterator.hasNext(); ) { if (AssignmentService.allowGradeSubmission(((Assignment) aIterator.next()).getReference())) { allowGradeSubmission = true; } } state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, new Boolean(allowGradeSubmission)); context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); // allow remove assignment? boolean allowRemoveAssignment = false; for (Iterator aIterator=assignments.iterator(); !allowRemoveAssignment && aIterator.hasNext(); ) { if (AssignmentService.allowRemoveAssignment(((Assignment) aIterator.next()).getReference())) { allowRemoveAssignment = true; } } context.put("allowRemoveAssignment", Boolean.valueOf(allowRemoveAssignment)); add2ndToolbarFields(data, context); // inform the observing courier that we just updated the page... // if there are pending requests to do so they can be cleared justDelivered(state); pagingInfoToContext(state, context); // put site object into context try { // get current site Site site = SiteService.getSite(contextString); context.put("site", site); // any group in the site? Collection groups = site.getGroups(); context.put("groups", (groups != null && groups.size()>0)?Boolean.TRUE:Boolean.FALSE); // add active user list AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString)); if (realm != null) { context.put("activeUserIds", realm.getUsers()); } } catch (Exception ignore) { Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString); } boolean allowSubmit = AssignmentService.allowAddSubmission(contextString); context.put("allowSubmit", new Boolean(allowSubmit)); // related to resubmit settings context.put("allowResubmitNumberProp", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); context.put("allowResubmitCloseTimeProp", AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); // the type int for non-electronic submission context.put("typeNonElectronic", Integer.valueOf(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_LIST_ASSIGNMENTS; } // build_list_assignments_context private HashSet<String> getSubmittersIdSet(List submissions) { HashSet<String> rv = new HashSet<String>(); for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext();) { List submitterIds = ((AssignmentSubmission) iSubmissions.next()).getSubmitterIds(); if (submitterIds != null && submitterIds.size() > 0) { rv.add((String) submitterIds.get(0)); } } return rv; } private HashSet<String> getAllowAddSubmissionUsersIdSet(List users) { HashSet<String> rv = new HashSet<String>(); for (Iterator iUsers=users.iterator(); iUsers.hasNext();) { rv.add(((User) iUsers.next()).getId()); } return rv; } /** * build the instructor view of creating a new assignment or editing an existing one */ protected String build_instructor_new_edit_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // is the assignment an new assignment String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID); if (assignmentId != null) { try { Assignment a = AssignmentService.getAssignment(assignmentId); context.put("assignment", a); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3") + ": " + assignmentId); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14") + ": " + assignmentId); } } // set up context variables setAssignmentFormContext(state, context); context.put("fField", state.getAttribute(NEW_ASSIGNMENT_FOCUS)); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT; } // build_instructor_new_assignment_context protected void setAssignmentFormContext(SessionState state, Context context) { // put the names and values into vm file context.put("name_UseReviewService", NEW_ASSIGNMENT_USE_REVIEW_SERVICE); context.put("name_AllowStudentView", NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW); context.put("name_title", NEW_ASSIGNMENT_TITLE); context.put("name_order", NEW_ASSIGNMENT_ORDER); // set open time context variables putTimePropertiesInContext(context, state, "Open", NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM); // set due time context variables putTimePropertiesInContext(context, state, "Due", NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM); context.put("name_EnableCloseDate", NEW_ASSIGNMENT_ENABLECLOSEDATE); // set close time context variables putTimePropertiesInContext(context, state, "Close", NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM); context.put("name_Section", NEW_ASSIGNMENT_SECTION); context.put("name_SubmissionType", NEW_ASSIGNMENT_SUBMISSION_TYPE); context.put("name_GradeType", NEW_ASSIGNMENT_GRADE_TYPE); context.put("name_GradePoints", NEW_ASSIGNMENT_GRADE_POINTS); context.put("name_Description", NEW_ASSIGNMENT_DESCRIPTION); // do not show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null) context.put("name_CheckAddDueDate", ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); //don't show the choice when there is no Announcement tool yet if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null) context.put("name_CheckAutoAnnounce", ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); context.put("name_CheckAddHonorPledge", NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // number of resubmissions allowed context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // set the values context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); context.put("value_title", state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("value_position_order", state.getAttribute(NEW_ASSIGNMENT_ORDER)); context.put("value_EnableCloseDate", state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)); context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_totalSubmissionTypes", Assignment.SUBMISSION_TYPES.length); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); // format to show one decimal place String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); // Keep the use review service setting context.put("value_UseReviewService", state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE)); context.put("value_AllowStudentView", state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW)); // don't show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null) context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); // don't show the choice when there is no Announcement tool yet if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null) context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); String s = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); if (s == null) s = "1"; context.put("value_CheckAddHonorPledge", s); // number of resubmissions allowed if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER))); } else { // defaults to 0 context.put("value_allowResubmitNumber", Integer.valueOf(0)); } // get all available assignments from Gradebook tool except for those created from boolean gradebookExists = isGradebookDefined(); if (gradebookExists) { GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); try { // get all assignments in Gradebook List gradebookAssignments = g.getAssignments(gradebookUid); List gradebookAssignmentsExceptSamigo = new Vector(); // filtering out those from Samigo for (Iterator i=gradebookAssignments.iterator(); i.hasNext();) { org.sakaiproject.service.gradebook.shared.Assignment gAssignment = (org.sakaiproject.service.gradebook.shared.Assignment) i.next(); if (!gAssignment.isExternallyMaintained() || gAssignment.isExternallyMaintained() && gAssignment.getExternalAppName().equals(getToolTitle())) { gradebookAssignmentsExceptSamigo.add(gAssignment); } } context.put("gradebookAssignments", gradebookAssignmentsExceptSamigo); if (StringUtil.trimToNull((String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null) { state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); } context.put("withGradebook", Boolean.TRUE); // offer the gradebook integration choice only in the Assignments with Grading tool boolean withGrade = ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(); if (withGrade) { context.put("name_Addtogradebook", AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); context.put("name_AssociateGradebookAssignment", AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); } context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("gradebookChoice_no", AssignmentService.GRADEBOOK_INTEGRATION_NO); context.put("gradebookChoice_add", AssignmentService.GRADEBOOK_INTEGRATION_ADD); context.put("gradebookChoice_associate", AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (associateGradebookAssignment != null) { context.put("associateGradebookAssignment", associateGradebookAssignment); String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID); if (assignmentId != null) { try { Assignment a = AssignmentService.getAssignment(assignmentId); context.put("noAddToGradebookChoice", Boolean.valueOf(associateGradebookAssignment.equals(a.getReference()))); } catch (Exception ee) { // ignore } } } } catch (Exception e) { // not able to link to Gradebook Log.warn("chef", this + e.getMessage()); } if (StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null) { state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); } } context.put("monthTable", monthTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String range = StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_RANGE)); if (range != null) { context.put("range", range); } String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // put site object into context try { // get current site Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", site); } catch (Exception ignore) { } if (AssignmentService.getAllowGroupAssignments()) { Collection groupsAllowAddAssignment = AssignmentService.getGroupsAllowAddAssignment(contextString); if (range == null) { if (AssignmentService.allowAddSiteAssignment(contextString)) { // default to make site selection context.put("range", "site"); } else if (groupsAllowAddAssignment.size() > 0) { // to group otherwise context.put("range", "groups"); } } // group list which user can add message to if (groupsAllowAddAssignment.size() > 0) { String sort = (String) state.getAttribute(SORTED_BY); String asc = (String) state.getAttribute(SORTED_ASC); if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION))) { sort = SORTED_BY_GROUP_TITLE; asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sort); state.setAttribute(SORTED_ASC, asc); } context.put("groups", new SortedIterator(groupsAllowAddAssignment.iterator(), new AssignmentComparator(state, sort, asc))); context.put("assignmentGroups", state.getAttribute(NEW_ASSIGNMENT_GROUPS)); } } context.put("allowGroupAssignmentsInGradebook", new Boolean(AssignmentService.getAllowGroupAssignmentsInGradebook())); // the notification email choices if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) != null && ((Boolean) state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS)).booleanValue()) { context.put("name_assignment_instructor_notifications", ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) == null) { // set the notification value using site default state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT)); } context.put("value_assignment_instructor_notifications", state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); // the option values context.put("value_assignment_instructor_notifications_none", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE); context.put("value_assignment_instructor_notifications_each", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH); context.put("value_assignment_instructor_notifications_digest", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST); } } // setAssignmentFormContext /** * build the instructor view of create a new assignment */ protected String build_instructor_preview_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("time", TimeService.newTime()); context.put("user", UserDirectoryService.getCurrentUser()); context.put("value_Title", (String) state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("name_order", NEW_ASSIGNMENT_ORDER); context.put("value_position_order", (String) state.getAttribute(NEW_ASSIGNMENT_ORDER)); Time openTime = getOpenTime(state); context.put("value_OpenDate", openTime); // due time int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue(); int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue(); int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue(); int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue(); int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue(); String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); context.put("value_DueDate", dueTime); // close time Time closeTime = TimeService.newTime(); Boolean enableCloseDate = (Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE); context.put("value_EnableCloseDate", enableCloseDate); if ((enableCloseDate).booleanValue()) { int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); context.put("value_CloseDate", closeTime); } context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); context.put("value_CheckAddHonorPledge", state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE)); // get all available assignments from Gradebook tool except for those created from if (isGradebookDefined()) { context.put("gradebookChoice", state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); } context.put("monthTable", monthTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("preview_assignment_assignment_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG)); context.put("preview_assignment_student_view_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG)); String assignmentId = StringUtil.trimToNull((String) state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID)); if (assignmentId != null) { // editing existing assignment context.put("value_assignment_id", assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); context.put("isDraft", Boolean.valueOf(a.getDraft())); } catch (Exception e) { Log.warn("chef", this + e.getMessage() + assignmentId); } } else { // new assignment context.put("isDraft", Boolean.TRUE); } context.put("value_assignmentcontent_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID)); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT; } // build_instructor_preview_assignment_context /** * build the instructor view to delete an assignment */ protected String build_instructor_delete_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { Vector assignments = new Vector(); Vector assignmentIds = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < assignmentIds.size(); i++) { try { Assignment a = AssignmentService.getAssignment((String) assignmentIds.get(i)); Iterator submissions = AssignmentService.getSubmissions(a).iterator(); if (submissions.hasNext()) { // if there is submission to the assignment, show the alert addAlert(state, rb.getString("areyousur") + " \"" + a.getTitle() + "\" " + rb.getString("whihassub") + "\n"); } assignments.add(a); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } context.put("assignments", assignments); context.put("service", AssignmentService.getInstance()); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT; } // build_instructor_delete_assignment_context /** * build the instructor view to grade an submission */ protected String build_instructor_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { int gradeType = -1; // need to show the alert for grading drafts? boolean addGradeDraftAlert = false; // assignment Assignment a = null; try { a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // assignment submission try { AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)); if (s != null) { context.put("submission", s); // show alert if student is working on a draft if (!s.getSubmitted() // not submitted && ((s.getSubmittedText() != null && s.getSubmittedText().length()> 0) // has some text || (s.getSubmittedAttachments() != null && s.getSubmittedAttachments().size() > 0))) // has some attachment { if (s.getCloseTime().after(TimeService.newTime())) { // not pass the close date yet addGradeDraftAlert = true; } else { // passed the close date already addGradeDraftAlert = false; } } ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER))); String allowResubmitTimeString =p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); Time allowResubmitTime = null; if (allowResubmitTimeString != null) { // if there is a local setting allowResubmitTime = TimeService.newTime(Long.parseLong(allowResubmitTimeString)); } else if (a != null) { // if there is no local setting, default to assignment close time allowResubmitTime = a.getCloseTime(); } // set up related state variables putTimePropertiesInState(state, allowResubmitTime, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM); // put allow resubmit time information into context putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } context.put("user", state.getAttribute(STATE_USER)); context.put("submissionTypeTable", submissionTypeTable()); context.put("instructorAttachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // names context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID); context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT); context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); context.put("name_grade", GRADE_SUBMISSION_GRADE); context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // values context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); context.put("value_grade_assignment_id", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("value_feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("value_feedback_text", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT)); context.put("value_feedback_attachment", state.getAttribute(ATTACHMENTS)); // format to show one decimal place in grade context.put("value_grade", (gradeType == 3) ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE)) : state.getAttribute(GRADE_SUBMISSION_GRADE)); context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG)); context.put("gradingAttachments", state.getAttribute(ATTACHMENTS)); // is this a non-electronic submission type of assignment context.put("nonElectronic", (a!=null && a.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)?Boolean.TRUE:Boolean.FALSE); if (addGradeDraftAlert) { addAlert(state, rb.getString("grading.alert.draft.beforeclosedate")); } context.put("alertGradeDraft", Boolean.valueOf(addGradeDraftAlert)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION; } // build_instructor_grade_submission_context /** * Parse time value and put corresponding values into state * @param context * @param state * @param a * @param timeValue * @param timeName * @param month * @param day * @param year * @param hour * @param min * @param ampm */ private void putTimePropertiesInState(SessionState state, Time timeValue, String month, String day, String year, String hour, String min, String ampm) { TimeBreakdown bTime = timeValue.breakdownLocal(); state.setAttribute(month, new Integer(bTime.getMonth())); state.setAttribute(day, new Integer(bTime.getDay())); state.setAttribute(year, new Integer(bTime.getYear())); int bHour = bTime.getHour(); if (bHour >= 12) { state.setAttribute(ampm, "PM"); } else { state.setAttribute(ampm, "AM"); } if (bHour == 0) { // for midnight point, we mark it as 12AM bHour = 12; } state.setAttribute(hour, new Integer((bHour > 12) ? bHour - 12 : bHour)); state.setAttribute(min, new Integer(bTime.getMin())); } /** * put related time information into context variable * @param context * @param state * @param timeName * @param month * @param day * @param year * @param hour * @param min * @param ampm */ private void putTimePropertiesInContext(Context context, SessionState state, String timeName, String month, String day, String year, String hour, String min, String ampm) { // get the submission level of close date setting context.put("name_" + timeName + "Month", month); context.put("name_" + timeName + "Day", day); context.put("name_" + timeName + "Year", year); context.put("name_" + timeName + "Hour", hour); context.put("name_" + timeName + "Min", min); context.put("name_" + timeName + "AMPM", ampm); context.put("value_" + timeName + "Month", (Integer) state.getAttribute(month)); context.put("value_" + timeName + "Day", (Integer) state.getAttribute(day)); context.put("value_" + timeName + "Year", (Integer) state.getAttribute(year)); context.put("value_" + timeName + "AMPM", (String) state.getAttribute(ampm)); context.put("value_" + timeName + "Hour", (Integer) state.getAttribute(hour)); context.put("value_" + timeName + "Min", (Integer) state.getAttribute(min)); } private List getPrevFeedbackAttachments(ResourceProperties p) { String attachmentsString = p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS); String[] attachmentsReferences = attachmentsString.split(","); List prevFeedbackAttachments = EntityManager.newReferenceList(); for (int k =0; k < attachmentsReferences.length; k++) { prevFeedbackAttachments.add(EntityManager.newReference(attachmentsReferences[k])); } return prevFeedbackAttachments; } /** * build the instructor preview of grading submission */ protected String build_instructor_preview_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // assignment int gradeType = -1; try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } // submission try { context.put("submission", AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID))); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } User user = (User) state.getAttribute(STATE_USER); context.put("user", user); context.put("submissionTypeTable", submissionTypeTable()); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // filter the feedback text for the instructor comment and mark it as red String feedbackText = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("feedback_text", feedbackText); context.put("feedback_attachment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT)); // format to show one decimal place String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); if (gradeType == 3) { grade = displayGrade(state, grade); } context.put("grade", grade); context.put("comment_open", COMMENT_OPEN); context.put("comment_close", COMMENT_CLOSE); context.put("allowResubmitNumber", state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); if (closeTimeString != null) { // close time for resubmit Time time = TimeService.newTime(Long.parseLong(closeTimeString)); context.put("allowResubmitCloseTime", time.toStringLocalFull()); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION; } // build_instructor_preview_grade_submission_context /** * build the instructor view to grade an assignment */ protected String build_instructor_grade_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("user", state.getAttribute(STATE_USER)); // sorting related fields context.put("sortedBy", state.getAttribute(SORTED_GRADE_SUBMISSION_BY)); context.put("sortedAsc", state.getAttribute(SORTED_GRADE_SUBMISSION_ASC)); context.put("sort_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME); context.put("sort_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME); context.put("sort_submitStatus", SORTED_GRADE_SUBMISSION_BY_STATUS); context.put("sort_submitGrade", SORTED_GRADE_SUBMISSION_BY_GRADE); context.put("sort_submitReleased", SORTED_GRADE_SUBMISSION_BY_RELEASED); context.put("sort_submitReview", SORTED_GRADE_SUBMISSION_CONTENTREVIEW); Assignment assignment = null; try { assignment = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); context.put("assignment", assignment); state.setAttribute(EXPORT_ASSIGNMENT_ID, assignment.getId()); // ever set the default grade for no-submissions String defaultGrade = assignment.getProperties().getProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE); if (defaultGrade != null) { context.put("defaultGrade", defaultGrade); } // groups if (state.getAttribute(VIEW_SUBMISSION_LIST_OPTION) == null) { state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, rb.getString("gen.viewallgroupssections")); } String view = (String)state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); context.put("view", view); // access point url for zip file download String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String accessPointUrl = ServerConfigurationService.getAccessUrl().concat(AssignmentService.submissionsZipReference( contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF))); if (!view.equals(rb.getString("gen.viewallgroupssections"))) { // append the group info to the end accessPointUrl = accessPointUrl.concat(view); } context.put("accessPointUrl", accessPointUrl); if (AssignmentService.getAllowGroupAssignments()) { Collection groupsAllowGradeAssignment = AssignmentService.getGroupsAllowGradeAssignment((String) state.getAttribute(STATE_CONTEXT_STRING), assignment.getReference()); // group list which user can add message to if (groupsAllowGradeAssignment.size() > 0) { String sort = (String) state.getAttribute(SORTED_BY); String asc = (String) state.getAttribute(SORTED_ASC); if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION))) { sort = SORTED_BY_GROUP_TITLE; asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sort); state.setAttribute(SORTED_ASC, asc); } context.put("groups", new SortedIterator(groupsAllowGradeAssignment.iterator(), new AssignmentComparator(state, sort, asc))); } } // for non-electronic assignment if (assignment.getContent() != null && assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { updateNonElectronicSubmissions(state, assignment); } List userSubmissions = prepPage(state); state.setAttribute(USER_SUBMISSIONS, userSubmissions); context.put("userSubmissions", state.getAttribute(USER_SUBMISSIONS)); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("submissionTypeTable", submissionTypeTable()); context.put("attachments", state.getAttribute(ATTACHMENTS)); // Get turnitin results for instructors context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); context.put("assignment_expand_flag", state.getAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG)); context.put("submission_expand_flag", state.getAttribute(GRADE_SUBMISSION_EXPAND_FLAG)); // the user directory service context.put("userDirectoryService", UserDirectoryService.getInstance()); add2ndToolbarFields(data, context); pagingInfoToContext(state, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT; } // build_instructor_grade_assignment_context /** * Synchronize the submissions for non electronic assignment with the current user set * @param state * @param assignment */ private void updateNonElectronicSubmissions(SessionState state, Assignment assignment) { List submissions = AssignmentService.getSubmissions(assignment); // the following operation is accessible for those with add assignment right List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers(assignment.getReference()); HashSet<String> submittersIdSet = getSubmittersIdSet(submissions); HashSet<String> allowAddSubmissionUsersIdSet = getAllowAddSubmissionUsersIdSet(allowAddSubmissionUsers); if (!submittersIdSet.equals(allowAddSubmissionUsersIdSet)) { // get the difference between two sets try { HashSet<String> addSubmissionUserIdSet = (HashSet<String>) allowAddSubmissionUsersIdSet.clone(); addSubmissionUserIdSet.removeAll(submittersIdSet); HashSet<String> removeSubmissionUserIdSet = (HashSet<String>) submittersIdSet.clone(); removeSubmissionUserIdSet.removeAll(allowAddSubmissionUsersIdSet); try { addRemoveSubmissionsForNonElectronicAssignment(state, submissions, addSubmissionUserIdSet, removeSubmissionUserIdSet, assignment); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } catch (Exception e) { Log.warn("chef", this + e.getMessage()); } } } /** * build the instructor view of an assignment */ protected String build_instructor_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("tlang", rb); Assignment assignment = null; try { assignment = AssignmentService.getAssignment((String) state.getAttribute(VIEW_ASSIGNMENT_ID)); context.put("assignment", assignment); // the creator String creatorId = assignment.getCreator(); try { User creator = UserDirectoryService.getUser(creatorId); context.put("creator", creator.getDisplayName()); } catch (Exception ee) { context.put("creator", creatorId); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> activityHelpers = new ArrayList<TaggingHelperInfo>(); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getActivityHelperInfo( assignmentActivityProducer.getActivity( assignment).getReference()); if (helper != null) { activityHelpers.add(helper); } } addActivity(context, assignment); context.put("activityHelpers", activityHelpers); context.put("taggable", Boolean.valueOf(true)); } context.put("currentTime", TimeService.newTime()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hideAssignmentFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG)); context.put("hideStudentViewFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT; } // build_instructor_view_assignment_context /** * build the instructor view of reordering assignments */ protected String build_instructor_reorder_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); List assignments = prepPage(state); context.put("assignments", assignments.iterator()); context.put("assignmentsize", assignments.size()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); // put site object into context try { // get current site Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", site); } catch (Exception ignore) { } context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT; } // build_instructor_reorder_assignment_context /** * build the instructor view to view the list of students for an assignment */ protected String build_instructor_view_students_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // get the realm and its member List studentMembers = new Vector(); List allowSubmitMembers = AssignmentService.allowAddAnySubmissionUsers(contextString); for (Iterator allowSubmitMembersIterator=allowSubmitMembers.iterator(); allowSubmitMembersIterator.hasNext();) { // get user try { String userId = (String) allowSubmitMembersIterator.next(); User user = UserDirectoryService.getUser(userId); studentMembers.add(user); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } context.put("studentMembers", new SortedIterator(studentMembers.iterator(), new AssignmentComparator(state, SORTED_USER_BY_SORTNAME, Boolean.TRUE.toString()))); context.put("assignmentService", AssignmentService.getInstance()); Hashtable showStudentAssignments = new Hashtable(); if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) != null) { Set showStudentListSet = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); context.put("studentListShowSet", showStudentListSet); for (Iterator showStudentListSetIterator=showStudentListSet.iterator(); showStudentListSetIterator.hasNext();) { // get user try { String userId = (String) showStudentListSetIterator.next(); User user = UserDirectoryService.getUser(userId); // sort the assignments into the default order before adding Iterator assignmentSorter = AssignmentService.getAssignmentsForContext(contextString, userId); // filter to obtain only grade-able assignments List rv = new Vector(); while (assignmentSorter.hasNext()) { Assignment a = (Assignment) assignmentSorter.next(); if (AssignmentService.allowGradeSubmission(a.getReference())) { rv.add(a); } } Iterator assignmentSortFinal = new SortedIterator(rv.iterator(), new AssignmentComparator(state, SORTED_BY_DEFAULT, Boolean.TRUE.toString())); showStudentAssignments.put(user, assignmentSortFinal); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } } context.put("studentAssignmentsTable", showStudentAssignments); add2ndToolbarFields(data, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT; } // build_instructor_view_students_assignment_context /** * build the instructor view to report the submissions */ protected String build_instructor_report_submissions(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("submissions", prepPage(state)); context.put("sortedBy", (String) state.getAttribute(SORTED_SUBMISSION_BY)); context.put("sortedAsc", (String) state.getAttribute(SORTED_SUBMISSION_ASC)); context.put("sortedBy_lastName", SORTED_SUBMISSION_BY_LASTNAME); context.put("sortedBy_submitTime", SORTED_SUBMISSION_BY_SUBMIT_TIME); context.put("sortedBy_grade", SORTED_SUBMISSION_BY_GRADE); context.put("sortedBy_status", SORTED_SUBMISSION_BY_STATUS); context.put("sortedBy_released", SORTED_SUBMISSION_BY_RELEASED); context.put("sortedBy_assignment", SORTED_SUBMISSION_BY_ASSIGNMENT); context.put("sortedBy_maxGrade", SORTED_SUBMISSION_BY_MAX_GRADE); add2ndToolbarFields(data, context); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("accessPointUrl", ServerConfigurationService.getAccessUrl() + AssignmentService.gradesSpreadsheetReference(contextString, null)); pagingInfoToContext(state, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS; } // build_instructor_report_submissions // Is Gradebook defined for the site? protected boolean isGradebookDefined() { boolean rv = false; try { GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager .get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); if (g.isGradebookDefined(gradebookUid)) { rv = true; } } catch (Exception e) { Log.debug("chef", this + rb.getString("addtogradebook.alertMessage") + "\n" + e.getMessage()); } return rv; } // isGradebookDefined() /** * build the instructor view to upload information from archive file */ protected String build_instructor_upload_all(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("hasSubmissionText", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT)); context.put("hasSubmissionAttachment", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT)); context.put("hasGradeFile", state.getAttribute(UPLOAD_ALL_HAS_GRADEFILE)); context.put("hasComments", state.getAttribute(UPLOAD_ALL_HAS_COMMENTS)); context.put("hasFeedbackText", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT)); context.put("hasFeedbackAttachment", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT)); context.put("releaseGrades", state.getAttribute(UPLOAD_ALL_RELEASE_GRADES)); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("accessPointUrl", (ServerConfigurationService.getAccessUrl()).concat(AssignmentService.submissionsZipReference( contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF)))); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_UPLOAD_ALL; } // build_instructor_upload_all /** ** Retrieve tool title from Tool configuration file or use default ** (This should return i18n version of tool title if available) **/ private String getToolTitle() { Tool tool = ToolManager.getTool(ASSIGNMENT_TOOL_ID); String toolTitle = null; if (tool == null) toolTitle = "Assignments"; else toolTitle = tool.getTitle(); return toolTitle; } /** * integration with gradebook * * @param state * @param assignmentRef Assignment reference * @param associateGradebookAssignment The title for the associated GB assignment * @param addUpdateRemoveAssignment "add" for adding the assignment; "update" for updating the assignment; "remove" for remove assignment * @param oldAssignment_title The original assignment title * @param newAssignment_title The updated assignment title * @param newAssignment_maxPoints The maximum point of the assignment * @param newAssignment_dueTime The due time of the assignment * @param submissionRef Any submission grade need to be updated? Do bulk update if null * @param updateRemoveSubmission "update" for update submission;"remove" for remove submission */ protected void integrateGradebook (SessionState state, String assignmentRef, String associateGradebookAssignment, String addUpdateRemoveAssignment, String oldAssignment_title, String newAssignment_title, int newAssignment_maxPoints, Time newAssignment_dueTime, String submissionRef, String updateRemoveSubmission) { associateGradebookAssignment = StringUtil.trimToNull(associateGradebookAssignment); // add or remove external grades to gradebook // a. if Gradebook does not exists, do nothing, 'cos setting should have been hidden // b. if Gradebook exists, just call addExternal and removeExternal and swallow any exception. The // exception are indication that the assessment is already in the Gradebook or there is nothing // to remove. String assignmentToolTitle = getToolTitle(); GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); if (g.isGradebookDefined(gradebookUid)) { boolean isExternalAssignmentDefined=g.isExternalAssignmentDefined(gradebookUid, assignmentRef); boolean isExternalAssociateAssignmentDefined = g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment); boolean isAssignmentDefined = g.isAssignmentDefined(gradebookUid, associateGradebookAssignment); if (addUpdateRemoveAssignment != null) { // add an entry into Gradebook for newly created assignment or modified assignment, and there wasn't a correspond record in gradebook yet if ((addUpdateRemoveAssignment.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD) || (addUpdateRemoveAssignment.equals("update") && !isExternalAssignmentDefined)) && associateGradebookAssignment == null) { // add assignment into gradebook try { // add assignment to gradebook g.addExternalAssessment(gradebookUid, assignmentRef, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), assignmentToolTitle); } catch (AssignmentHasIllegalPointsException e) { addAlert(state, rb.getString("addtogradebook.illegalPoints")); } catch (ConflictingAssignmentNameException e) { // add alert prompting for change assignment title addAlert(state, rb.getString("addtogradebook.nonUniqueTitle")); } catch (ConflictingExternalIdException e) { // this shouldn't happen, as we have already checked for assignment reference before. Log the error Log.warn("chef", this + e.getMessage()); } catch (GradebookNotFoundException e) { // this shouldn't happen, as we have checked for gradebook existence before Log.warn("chef", this + e.getMessage()); } catch (Exception e) { // ignore Log.warn("chef", this + e.getMessage()); } } else if (addUpdateRemoveAssignment.equals("update")) { if (associateGradebookAssignment != null && isExternalAssociateAssignmentDefined) { // if there is an external entry created in Gradebook based on this assignment, update it try { Assignment a = AssignmentService.getAssignment(associateGradebookAssignment); // update attributes if the GB assignment was created for the assignment g.updateExternalAssessment(gradebookUid, associateGradebookAssignment, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime())); } catch(Exception e) { Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage()); } } } // addUpdateRemove != null else if (addUpdateRemoveAssignment.equals("remove")) { // remove assignment and all submission grades removeNonAssociatedExternalGradebookEntry((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentRef, associateGradebookAssignment, g, gradebookUid); } } if (updateRemoveSubmission != null) { try { Assignment a = AssignmentService.getAssignment(assignmentRef); if (updateRemoveSubmission.equals("update") && a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null && !a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK).equals(AssignmentService.GRADEBOOK_INTEGRATION_NO) && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { if (submissionRef == null) { // bulk add all grades for assignment into gradebook Iterator submissions = AssignmentService.getSubmissions(a).iterator(); Map m = new HashMap(); // any score to copy over? get all the assessmentGradingData and copy over while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); if (aSubmission.getGradeReleased()) { User[] submitters = aSubmission.getSubmitters(); String submitterId = submitters[0].getId(); String gradeString = StringUtil.trimToNull(aSubmission.getGrade()); Double grade = gradeString != null ? Double.valueOf(displayGrade(state,gradeString)) : null; m.put(submitterId, grade); } } // need to update only when there is at least one submission if (m.size()>0) { if (associateGradebookAssignment != null) { if (isExternalAssociateAssignmentDefined) { // the associated assignment is externally maintained g.updateExternalAssessmentScores(gradebookUid, associateGradebookAssignment, m); } else if (isAssignmentDefined) { // the associated assignment is internal one, update records one by one submissions = AssignmentService.getSubmissions(a).iterator(); while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); User[] submitters = aSubmission.getSubmitters(); String submitterId = submitters[0].getId(); String gradeString = StringUtil.trimToNull(aSubmission.getGrade()); Double grade = (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null; g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitterId, grade, assignmentToolTitle); } } } else if (isExternalAssignmentDefined) { g.updateExternalAssessmentScores(gradebookUid, assignmentRef, m); } } } else { try { // only update one submission AssignmentSubmission aSubmission = (AssignmentSubmission) AssignmentService .getSubmission(submissionRef); User[] submitters = aSubmission.getSubmitters(); String gradeString = StringUtil.trimToNull(aSubmission.getGrade()); if (associateGradebookAssignment != null) { if (g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment)) { // the associated assignment is externally maintained g.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null); } else if (g.isAssignmentDefined(gradebookUid, associateGradebookAssignment)) { // the associated assignment is internal one, update records g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null, assignmentToolTitle); } } else { g.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(), (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null); } } catch (Exception e) { Log.warn("chef", "Cannot find submission " + submissionRef + ": " + e.getMessage()); } } } else if (updateRemoveSubmission.equals("remove")) { if (submissionRef == null) { // remove all submission grades (when changing the associated entry in Gradebook) Iterator submissions = AssignmentService.getSubmissions(a).iterator(); // any score to copy over? get all the assessmentGradingData and copy over while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); User[] submitters = aSubmission.getSubmitters(); if (isExternalAssociateAssignmentDefined) { // if the old associated assignment is an external maintained one g.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null); } else if (isAssignmentDefined) { g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null, assignmentToolTitle); } } } else { // remove only one submission grade try { AssignmentSubmission aSubmission = (AssignmentSubmission) AssignmentService .getSubmission(submissionRef); User[] submitters = aSubmission.getSubmitters(); g.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(), null); } catch (Exception e) { Log.warn("chef", "Cannot find submission " + submissionRef + ": " + e.getMessage()); } } } } catch (Exception e) { Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage()); } } // updateRemoveSubmission != null } } // integrateGradebook /** * Go to the instructor view */ public void doView_instructor(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doView_instructor /** * Go to the student view */ public void doView_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // to the student list of assignment view state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doView_student /** * Action is to view the content of one specific assignment submission */ public void doView_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); String assignmentReference = params.getString("assignmentReference"); state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, assignmentReference); User u = (User) state.getAttribute(STATE_USER); try { AssignmentSubmission submission = AssignmentService.getSubmission(assignmentReference, u); if (submission != null) { state.setAttribute(VIEW_SUBMISSION_TEXT, submission.getSubmittedText()); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, (new Boolean(submission.getHonorPledgeFlag())).toString()); List v = EntityManager.newReferenceList(); Iterator l = submission.getSubmittedAttachments().iterator(); while (l.hasNext()) { v.add(l.next()); } state.setAttribute(ATTACHMENTS, v); } else { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // try } // doView_submission /** * Action is to view the content of one specific assignment submission */ public void doView_submission_list_option(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String view = params.getString("view"); state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, view); } // doView_submission_list_option /** * Preview of the submission */ public void doPreview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // String assignmentId = params.getString(assignmentId); state.setAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE, state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE)); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(PREVIEW_SUBMISSION_TEXT, text); state.setAttribute(VIEW_SUBMISSION_TEXT, text); // assign the honor pledge attribute String honor_pledge_yes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honor_pledge_yes == null) { honor_pledge_yes = "false"; } state.setAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(PREVIEW_SUBMISSION_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_PREVIEW_SUBMISSION); } } // doPreview_submission /** * Preview of the grading of submission */ public void doPreview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read user input readGradeForm(data, state, "read"); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION); } } // doPreview_grade_submission /** * Action is to end the preview submission process */ public void doDone_preview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } // doDone_preview_submission /** * Action is to end the view assignment process */ public void doDone_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doDone_view_assignments /** * Action is to end the preview new assignment process */ public void doDone_preview_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the new assignment page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doDone_preview_new_assignment /** * Action is to end the user view assignment process and redirect him to the assignment list view */ public void doCancel_student_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_student_view_assignment /** * Action is to end the show submission process */ public void doCancel_show_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_show_submission /** * Action is to cancel the delete assignment process */ public void doCancel_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the show assignment object state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); // back to the instructor list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_delete_assignment /** * Action is to end the show submission process */ public void doCancel_edit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset sorting setDefaultSort(state); } // doCancel_edit_assignment /** * Action is to end the show submission process */ public void doCancel_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object resetAssignment(state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset sorting setDefaultSort(state); } // doCancel_new_assignment /** * Action is to cancel the grade submission process */ public void doCancel_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object // resetAssignment (state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } // doCancel_grade_submission /** * Action is to cancel the preview grade process */ public void doCancel_preview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } // doCancel_preview_grade_submission /** * Action is to cancel the reorder process */ public void doCancel_reorder(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_reorder /** * Action is to cancel the preview grade process */ public void doCancel_preview_to_list_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } // doCancel_preview_to_list_submission /** * Action is to return to the view of list assignments */ public void doList_assignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doList_assignments /** * Action is to cancel the student view grade process */ public void doCancel_view_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view grade submission id state.setAttribute(VIEW_GRADE_SUBMISSION_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_view_grade /** * Action is to save the grade to submission */ public void doSave_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "save"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "save"); } } // doSave_grade_submission /** * Action is to release the grade to submission */ public void doRelease_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "release"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "release"); } } // doRelease_grade_submission /** * Action is to return submission with or without grade */ public void doReturn_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "return"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "return"); } } // doReturn_grade_submission /** * Action is to return submission with or without grade from preview */ public void doReturn_preview_grade_submission(RunData data) { grade_submission_option(data, "return"); } // doReturn_grade_preview_submission /** * Action is to save submission with or without grade from preview */ public void doSave_preview_grade_submission(RunData data) { grade_submission_option(data, "save"); } // doSave_grade_preview_submission /** * Common grading routine plus specific operation to differenciate cases when saving, releasing or returning grade. */ private void grade_submission_option(RunData data, String gradeOption) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(): false; String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); try { // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(sId); Assignment a = sEdit.getAssignment(); int typeOfGrade = a.getContent().getTypeOfGrade(); if (!withGrade) { // no grade input needed for the without-grade version of assignment tool sEdit.setGraded(true); if (gradeOption.equals("return") || gradeOption.equals("release")) { sEdit.setGradeReleased(true); } } else if (grade == null) { sEdit.setGrade(""); sEdit.setGraded(false); sEdit.setGradeReleased(false); } else { if (typeOfGrade == 1) { sEdit.setGrade(rb.getString("gen.nograd")); } else { sEdit.setGrade(grade); } if (grade.length() != 0) { sEdit.setGraded(true); } else { sEdit.setGraded(false); } } if (gradeOption.equals("release")) { sEdit.setGradeReleased(true); sEdit.setGraded(true); // clear the returned flag sEdit.setReturned(false); sEdit.setTimeReturned(null); } else if (gradeOption.equals("return")) { sEdit.setGradeReleased(true); sEdit.setGraded(true); sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); } else if (gradeOption.equals("save")) { sEdit.setGradeReleased(false); sEdit.setReturned(false); sEdit.setTimeReturned(null); } if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // get resubmit number ResourcePropertiesEdit pEdit = sEdit.getPropertiesEdit(); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null) { // get resubmit time Time closeTime = getAllowSubmitCloseTime(state); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); } else { pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } // the instructor comment String feedbackCommentString = StringUtil .trimToNull((String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); if (feedbackCommentString != null) { sEdit.setFeedbackComment(feedbackCommentString); } // the instructor inline feedback String feedbackTextString = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); if (feedbackTextString != null) { sEdit.setFeedbackText(feedbackTextString); } List v = (List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); if (v != null) { // clear the old attachments first sEdit.clearFeedbackAttachments(); for (int i = 0; i < v.size(); i++) { sEdit.addFeedbackAttachment((Reference) v.get(i)); } } String sReference = sEdit.getReference(); AssignmentService.commitEdit(sEdit); // update grades in gradebook String aReference = a.getReference(); String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (gradeOption.equals("release") || gradeOption.equals("return")) { // update grade in gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update"); } else { // remove grade from gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "remove"); } } catch (IdUnusedException e) { } catch (PermissionException e) { } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } // try if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } } // grade_submission_option /** * Action is to save the submission as a draft */ public void doSave_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = "false"; } String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); User u = (User) state.getAttribute(STATE_USER); if (state.getAttribute(STATE_MESSAGE) == null) { try { Assignment a = AssignmentService.getAssignment(aReference); String assignmentId = a.getId(); AssignmentSubmission submission = AssignmentService.getSubmission(aReference, u); if (submission != null) { // the submission already exists, change the text and honor pledge value, save as draft try { AssignmentSubmissionEdit edit = AssignmentService.editSubmission(submission.getReference()); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setSubmitted(false); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // clear the old attachments first edit.clearSubmittedAttachments(); // add each new attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle()); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot12")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } else { // new submission, save as draft try { AssignmentSubmissionEdit edit = AssignmentService.addSubmission((String) state .getAttribute(STATE_CONTEXT_STRING), assignmentId, SessionManager.getCurrentSessionUserId()); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setSubmitted(false); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot4")); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION); } } // doSave_submission /** * Action is to post the submission */ public void doPost_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment a = null; try { a = AssignmentService.getAssignment(aReference); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } if (AssignmentService.canSubmit(contextString, a)) { ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } else { state.setAttribute(VIEW_SUBMISSION_TEXT, text); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = (String) state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES); } if (honorPledgeYes == null) { honorPledgeYes = "false"; } User u = (User) state.getAttribute(STATE_USER); String assignmentId = ""; if (state.getAttribute(STATE_MESSAGE) == null) { assignmentId = a.getId(); if (a.getContent().getHonorPledge() != 1) { if (!Boolean.valueOf(honorPledgeYes).booleanValue()) { addAlert(state, rb.getString("youarenot18")); } state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honorPledgeYes); } // check the submission inputs based on the submission type int submissionType = a.getContent().getTypeOfSubmission(); if (submissionType == 1) { // for the inline only submission if (text.length() == 0) { addAlert(state, rb.getString("youmust7")); } } else if (submissionType == 2) { // for the attachment only submission Vector v = (Vector) state.getAttribute(ATTACHMENTS); if ((v == null) || (v.size() == 0)) { addAlert(state, rb.getString("youmust1")); } } else if (submissionType == 3) { // for the inline and attachment submission Vector v = (Vector) state.getAttribute(ATTACHMENTS); if ((text.length() == 0) && ((v == null) || (v.size() == 0))) { addAlert(state, rb.getString("youmust2")); } } } if ((state.getAttribute(STATE_MESSAGE) == null) && (a != null)) { try { AssignmentSubmission submission = AssignmentService.getSubmission(a.getReference(), u); if (submission != null) { // the submission already exists, change the text and honor pledge value, post it try { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setSubmittedText(text); sEdit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); sEdit.setTimeSubmitted(TimeService.newTime()); sEdit.setSubmitted(true); // for resubmissions // when resubmit, keep the Returned flag on till the instructor grade again. Time now = TimeService.newTime(); ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit(); if (sEdit.getGraded()) { // add the current grade into previous grade histroy String previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES); if (previousGrades == null) { previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); if (previousGrades != null) { int typeOfGrade = a.getContent().getTypeOfGrade(); if (typeOfGrade == 3) { // point grade assignment type // some old unscaled grades, need to scale the number and remove the old property String[] grades = StringUtil.split(previousGrades, " "); String newGrades = ""; for (int jj = 0; jj < grades.length; jj++) { String grade = grades[jj]; if (grade.indexOf(".") == -1) { // show the grade with decimal point grade = grade.concat(".0"); } newGrades = newGrades.concat(grade + " "); } previousGrades = newGrades; } sPropertiesEdit.removeProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); } else { previousGrades = ""; } } previousGrades = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />" + sEdit.getGradeDisplay() + "<p />" +previousGrades; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES, previousGrades); // clear the current grade and make the submission ungraded sEdit.setGraded(false); sEdit.setGrade(""); sEdit.setGradeReleased(false); // keep the history of assignment feed back text String feedbackTextHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) : ""; feedbackTextHistory = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />" + sEdit.getFeedbackText() + "<p />" + feedbackTextHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT, feedbackTextHistory); // keep the history of assignment feed back comment String feedbackCommentHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) : ""; feedbackCommentHistory = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />" + sEdit.getFeedbackComment() + "<p />" + feedbackCommentHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT, feedbackCommentHistory); // keep the history of assignment feed back comment String feedbackAttachmentHistory = sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null ? sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) : ""; List feedbackAttachments = sEdit.getFeedbackAttachments(); String att = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />"; for (int k = 0; k<feedbackAttachments.size();k++) { att = att + ((Reference) feedbackAttachments.get(k)).getReference() + "<p />"; } feedbackAttachmentHistory = att + feedbackAttachmentHistory; sPropertiesEdit.addProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS, feedbackAttachmentHistory); // reset the previous grading context sEdit.setFeedbackText(""); sEdit.setFeedbackComment(""); sEdit.clearFeedbackAttachments(); // decrease the allow_resubmit_number if (sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { int number = Integer.parseInt(sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); // minus 1 from the submit number if (number>=1) { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(number-1)); } else if (number == -1) { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(-1)); } } } sEdit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { //Post the attachments before clearing so that we don't sumbit duplicate attachments //Check if we need to post the attachments if (a.getContent().getAllowReviewService()) { if (!attachments.isEmpty()) { sEdit.postAttachment(attachments); } } // clear the old attachments first sEdit.clearSubmittedAttachments(); // add each new attachment Iterator it = attachments.iterator(); while (it.hasNext()) { sEdit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(sEdit); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle()); } catch (PermissionException e) { addAlert(state, rb.getString("no_permissiion_to_edit_submission")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } else { // new submission, post it try { AssignmentSubmissionEdit edit = AssignmentService.addSubmission(contextString, assignmentId, SessionManager.getCurrentSessionUserId()); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setTimeSubmitted(TimeService.newTime()); edit.setSubmitted(true); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // add each attachment if ((!attachments.isEmpty()) && a.getContent().getAllowReviewService()) edit.postAttachment(attachments); // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } // get the assignment setting for resubmitting if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { edit.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); } AssignmentService.commitEdit(edit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot13")); } } // if -else } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } } // if if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION); } } // if } // doPost_submission /** * Action is to confirm the submission and return to list view */ public void doConfirm_assignment_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } /** * Action is to show the new assignment screen */ public void doNew_assignment(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAddAssignment((String) state.getAttribute(STATE_CONTEXT_STRING))) { resetAssignment(state); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot2")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } } // doNew_Assignment /** * Action is to show the reorder assignment screen */ public void doReorder(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // this insures the default order is loaded into the reordering tool state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAllGroups((String) state.getAttribute(STATE_CONTEXT_STRING))) { resetAssignment(state); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REORDER_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot19")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } } // doReorder /** * Action is to save the input infos for assignment fields * * @param validify * Need to validify the inputs or not */ protected void setNewAssignmentParameters(RunData data, boolean validify) { // read the form inputs SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // put the input value into the state attributes String title = params.getString(NEW_ASSIGNMENT_TITLE); state.setAttribute(NEW_ASSIGNMENT_TITLE, title); String order = params.getString(NEW_ASSIGNMENT_ORDER); state.setAttribute(NEW_ASSIGNMENT_ORDER, order); if (title.length() == 0) { // empty assignment title addAlert(state, rb.getString("plespethe1")); } // open time int openMonth = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openMonth)); int openDay = (new Integer(params.getString(NEW_ASSIGNMENT_OPENDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openDay)); int openYear = (new Integer(params.getString(NEW_ASSIGNMENT_OPENYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openYear)); int openHour = (new Integer(params.getString(NEW_ASSIGNMENT_OPENHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(openHour)); int openMin = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openMin)); String openAMPM = params.getString(NEW_ASSIGNMENT_OPENAMPM); state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, openAMPM); if ((openAMPM.equals("PM")) && (openHour != 12)) { openHour = openHour + 12; } if ((openHour == 12) && (openAMPM.equals("AM"))) { openHour = 0; } Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0); // validate date if (!Validator.checkDate(openDay, openMonth, openYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.opendate") + "."); } // due time int dueMonth = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueMonth)); int dueDay = (new Integer(params.getString(NEW_ASSIGNMENT_DUEDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueDay)); int dueYear = (new Integer(params.getString(NEW_ASSIGNMENT_DUEYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueYear)); int dueHour = (new Integer(params.getString(NEW_ASSIGNMENT_DUEHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(dueHour)); int dueMin = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueMin)); String dueAMPM = params.getString(NEW_ASSIGNMENT_DUEAMPM); state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, dueAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); // show alert message when due date is in past. Remove it after user confirms the choice. if (dueTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) == null) { state.setAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE, Boolean.TRUE); } else { // clean the attribute after user confirm state.removeAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE); } if (state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) != null) { addAlert(state, rb.getString("assig4")); } if (!dueTime.after(openTime)) { addAlert(state, rb.getString("assig3")); } if (!Validator.checkDate(dueDay, dueMonth, dueYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.duedate") + "."); } state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); // close time int closeMonth = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeMonth)); int closeDay = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeDay)); int closeYear = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeYear)); int closeHour = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(closeHour)); int closeMin = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeMin)); String closeAMPM = params.getString(NEW_ASSIGNMENT_CLOSEAMPM); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, closeAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); // validate date if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + "."); } if (!closeTime.after(openTime)) { addAlert(state, rb.getString("acesubdea3")); } if (closeTime.before(dueTime)) { addAlert(state, rb.getString("acesubdea2")); } // SECTION MOD String sections_string = ""; String mode = (String) state.getAttribute(STATE_MODE); if (mode == null) mode = ""; state.setAttribute(NEW_ASSIGNMENT_SECTION, sections_string); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(params.getString(NEW_ASSIGNMENT_SUBMISSION_TYPE))); int gradeType = -1; // grade type and grade points if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { gradeType = Integer.parseInt(params.getString(NEW_ASSIGNMENT_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(gradeType)); } String r = params.getString(NEW_ASSIGNMENT_USE_REVIEW_SERVICE); String b; // set whether we use the review service or not if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, b); //set whether students can view the review service results r = params.getString(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, b); // treat the new assignment description as formatted text boolean checkForFormattingErrors = true; // instructor is creating a new assignment - so check for errors String description = processFormattedTextFromBrowser(state, params.getCleanString(NEW_ASSIGNMENT_DESCRIPTION), checkForFormattingErrors); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, description); if (state.getAttribute(CALENDAR) != null) { // calendar enabled for the site if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE).equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); } } else { // no calendar yet for the site state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) .equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); } String s = params.getString(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // set the honor pledge to be "no honor pledge" if (s == null) s = "1"; state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, s); String grading = params.getString(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, grading); // only when choose to associate with assignment in Gradebook String associateAssignment = params.getString(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (grading != null) { if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateAssignment); } else { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, ""); } if (!grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // gradebook integration only available to point-grade assignment if (gradeType != Assignment.SCORE_GRADE_TYPE) { addAlert(state, rb.getString("addtogradebook.wrongGradeScale")); } // if chosen as "associate", have to choose one assignment from Gradebook if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE) && StringUtil.trimToNull(associateAssignment) == null) { addAlert(state, rb.getString("grading.associate.alert")); } } } List attachments = (List) state.getAttribute(ATTACHMENTS); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, attachments); if (validify) { if (((description == null) || (description.length() == 0)) && ((attachments == null || attachments.size() == 0))) { // if there is no description nor an attachment, show the following alert message. // One could ignore the message and still post the assignment if (state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) == null) { state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY, Boolean.TRUE.toString()); } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } if (validify && state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) != null) { addAlert(state, rb.getString("thiasshas")); } // assignment range? String range = data.getParameters().getString("range"); state.setAttribute(NEW_ASSIGNMENT_RANGE, range); if (range.equals("groups")) { String[] groupChoice = data.getParameters().getStrings("selectedGroups"); if (groupChoice != null && groupChoice.length != 0) { state.setAttribute(NEW_ASSIGNMENT_GROUPS, new ArrayList(Arrays.asList(groupChoice))); } else { state.setAttribute(NEW_ASSIGNMENT_GROUPS, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } } else { state.removeAttribute(NEW_ASSIGNMENT_GROUPS); } if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { // the grade point String gradePoints = params.getString(NEW_ASSIGNMENT_GRADE_POINTS); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); if (gradePoints != null) { if (gradeType == 3) { if ((gradePoints.length() == 0)) { // in case of point grade assignment, user must specify maximum grade point addAlert(state, rb.getString("plespethe3")); } else { validPointGrade(state, gradePoints); // when scale is points, grade must be integer and less than maximum value if (state.getAttribute(STATE_MESSAGE) == null) { gradePoints = scalePointGrade(state, gradePoints); } state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); } } } } // allow resubmission numbers String nString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (nString != null) { state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, nString); } // assignment notification option String notiOption = params.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (notiOption != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, notiOption); } } // setNewAssignmentParameters /** * Action is to hide the preview assignment student view */ public void doHide_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); // save user input readGradeForm(data, state, "read"); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(true)); // save user input readGradeForm(data, state, "read"); } // doShow_submission_assignment_instruction /** * Action is to hide the preview assignment student view */ public void doHide_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true)); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(false)); } // doShow_preview_assignment_student_view /** * Action is to hide the preview assignment assignment infos */ public void doHide_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(true)); } // doHide_preview_assignment_assignment /** * Action is to show the preview assignment assignment info */ public void doShow_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false)); } // doShow_preview_assignment_assignment /** * Action is to hide the assignment option */ public void doHide_assignment_option(RunData data) { setNewAssignmentParameters(data, false); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(true)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, "eventSubmit_doShow_assignment_option"); } // doHide_assignment_option /** * Action is to show the assignment option */ public void doShow_assignment_option(RunData data) { setNewAssignmentParameters(data, false); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); } // doShow_assignment_option /** * Action is to hide the assignment content in the view assignment page */ public void doHide_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(true)); } // doHide_view_assignment /** * Action is to show the assignment content in the view assignment page */ public void doShow_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false)); } // doShow_view_assignment /** * Action is to hide the student view in the view assignment page */ public void doHide_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true)); } // doHide_view_student_view /** * Action is to show the student view in the view assignment page */ public void doShow_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(false)); } // doShow_view_student_view /** * Action is to post assignment */ public void doPost_assignment(RunData data) { // post assignment postOrSaveAssignment(data, "post"); } // doPost_assignment /** * Action is to tag items via an items tagging helper */ public void doHelp_items(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getItemsHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Iterator<String> keys = helperParms.keySet().iterator(); keys .hasNext();) { String key = keys.next(); state.setAttribute(key, helperParms.get(key)); } } // doHelp_items /** * Action is to tag an individual item via an item tagging helper */ public void doHelp_item(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String itemRef = params.getString(ITEM_REF); TaggingHelperInfo helperInfo = provider .getItemHelperInfo(itemRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Iterator<String> keys = helperParms.keySet().iterator(); keys .hasNext();) { String key = keys.next(); state.setAttribute(key, helperParms.get(key)); } } // doHelp_item /** * Action is to tag an activity via an activity tagging helper */ public void doHelp_activity(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getActivityHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (String key : helperParms.keySet()) { state.setAttribute(key, helperParms.get(key)); } } // doHelp_activity /** * post or save assignment */ private void postOrSaveAssignment(RunData data, String postOrSave) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean post = (postOrSave != null) && postOrSave.equals("post"); // assignment old title String aOldTitle = null; // assignment old associated Gradebook entry if any String oAssociateGradebookAssignment = null; String mode = (String) state.getAttribute(STATE_MODE); if (!mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)) { // read input data if the mode is not preview mode setNewAssignmentParameters(data, true); } String assignmentId = params.getString("assignmentId"); String assignmentContentId = params.getString("assignmentContentId"); // whether this is an editing which changes non-electronic assignment to any other type? boolean bool_change_from_non_electronic = false; if (state.getAttribute(STATE_MESSAGE) == null) { // AssignmentContent object AssignmentContentEdit ac = getAssignmentContentEdit(state, assignmentContentId); // Assignment AssignmentEdit a = getAssignmentEdit(state, assignmentId); bool_change_from_non_electronic = change_from_non_electronic(state, assignmentId, assignmentContentId, ac); // put the names and values into vm file String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE); String order = (String) state.getAttribute(NEW_ASSIGNMENT_ORDER); // open time Time openTime = getOpenTime(state); // due time Time dueTime = getDueTime(state); // close time Time closeTime = dueTime; boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue(); if (enableCloseDate) { closeTime = getCloseTime(state); } // sections String section = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION); int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue(); int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue(); String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION); String checkAddDueTime = state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)!=null?(String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE):null; String checkAutoAnnounce = (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); String addtoGradebook = state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null?(String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK):"" ; String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null; boolean useReviewService = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE)); boolean allowStudentViewReport = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW)); // the attachments List attachments = (List) state.getAttribute(ATTACHMENTS); List attachments1 = EntityManager.newReferenceList(attachments); // set group property String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE); Collection groups = new Vector(); try { Site site = SiteService.getSite(siteId); Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS); if (range.equals(Assignment.AssignmentAccess.GROUPED) && (groupChoice == null || groupChoice.size() == 0)) { // show alert if no group is selected for the group access assignment addAlert(state, rb.getString("java.alert.youchoosegroup")); } else if (groupChoice != null) { for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();) { String groupId = (String) iGroups.next(); groups.add(site.getGroup(groupId)); } } } catch (Exception e) { Log.warn("chef", this + e.getMessage()); } if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null)) { aOldTitle = a.getTitle(); // old open time Time oldOpenTime = a.getOpenTime(); // old due time Time oldDueTime = a.getDueTime(); // commit the changes to AssignmentContent object commitAssignmentContentEdit(state, ac, title, submissionType,useReviewService,allowStudentViewReport, gradeType, gradePoints, description, checkAddHonorPledge, attachments1); // set the Assignment Properties object ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit(); oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); editAssignmentProperties(a, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit, post); // the notification option if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // comment the changes to Assignment object commitAssignmentEdit(state, post, ac, a, title, openTime, dueTime, closeTime, enableCloseDate, section, range, groups); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); resetAssignment(state); } if (post) { // only if user is posting the assignment if (ac.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // update submissions updateNonElectronicSubmissions(state, a); } else if (bool_change_from_non_electronic) { // not non_electronic type any more List submissions = AssignmentService.getSubmissions(a); if (submissions != null && submissions.size() >0) { // assignment already exist and with submissions for (Iterator iSubmissions = submissions.iterator(); iSubmissions.hasNext();) { AssignmentSubmission s = (AssignmentSubmission) iSubmissions.next(); try { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference()); sEdit.setSubmitted(false); sEdit.setTimeSubmitted(null); AssignmentService.commitEdit(sEdit); } catch (Exception e) { Log.debug("chef", this + e.getMessage() + s.getReference()); } } } } // add the due date to schedule if the schedule exists integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit); // the open date been announced integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, oldOpenTime); // integrate with Gradebook try { initIntegrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range); } catch (AssignmentHasIllegalPointsException e) { addAlert(state, rb.getString("addtogradebook.illegalPoints")); } } //if } // if } // if // set default sorting setDefaultSort(state); } // doPost_assignment /** * */ private boolean change_from_non_electronic(SessionState state, String assignmentId, String assignmentContentId, AssignmentContentEdit ac) { // whether this is an editing which changes non-electronic assignment to any other type? if (StringUtil.trimToNull(assignmentId) != null && StringUtil.trimToNull(assignmentContentId) != null) { // editing if (ac.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION && ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // changing from non-electronic type return true; } } return false; } /** * default sorting */ private void setDefaultSort(SessionState state) { state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } /** * Add submission objects if necessary for non-electronic type of assignment * @param state * @param a */ private void addRemoveSubmissionsForNonElectronicAssignment(SessionState state, List submissions, HashSet<String> addSubmissionForUsers, HashSet<String> removeSubmissionForUsers, Assignment a) { // create submission object for those user who doesn't have one yet for (Iterator iUserIds = addSubmissionForUsers.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null) { // construct fake submissions for grading purpose AssignmentSubmissionEdit submission = AssignmentService.addSubmission(a.getContext(), a.getId(), userId); submission.setTimeSubmitted(TimeService.newTime()); submission.setSubmitted(true); submission.setAssignment(a); AssignmentService.commitEdit(submission); } } catch (Exception e) { Log.warn("chef", this + e.toString() + "error adding submission for userId = " + userId); } } // remove submission object for those who no longer in the site for (Iterator iUserIds = removeSubmissionForUsers.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); String submissionRef = null; // TODO: we don't have an efficient way to retrieve specific user's submission now, so until then, we still need to iterate the whole submission list for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext() && submissionRef == null;) { AssignmentSubmission submission = (AssignmentSubmission) iSubmissions.next(); List submitterIds = submission.getSubmitterIds(); if (submitterIds != null && submitterIds.size() > 0 && userId.equals((String) submitterIds.get(0))) { submissionRef = submission.getReference(); } } if (submissionRef != null) { try { AssignmentSubmissionEdit submissionEdit = AssignmentService.editSubmission(submissionRef); AssignmentService.removeSubmission(submissionEdit); } catch (Exception e) { Log.warn("chef", this + e.toString() + " error remove submission for userId = " + userId); } } } } private void initIntegrateWithGradebook(SessionState state, String siteId, String aOldTitle, String oAssociateGradebookAssignment, AssignmentEdit a, String title, Time dueTime, int gradeType, String gradePoints, String addtoGradebook, String associateGradebookAssignment, String range) { String context = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean gradebookExists = isGradebookDefined(); // only if the gradebook is defined if (gradebookExists) { GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); String aReference = a.getReference(); String addUpdateRemoveAssignment = "remove"; if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // if integrate with Gradebook if (!AssignmentService.getAllowGroupAssignmentsInGradebook() && (range.equals("groups"))) { // if grouped assignment is not allowed to add into Gradebook addAlert(state, rb.getString("java.alert.noGroupedAssignmentIntoGB")); String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); aEdit.getPropertiesEdit().removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); aEdit.getPropertiesEdit().removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null); } else { if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { addUpdateRemoveAssignment = AssignmentService.GRADEBOOK_INTEGRATION_ADD; } else if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { addUpdateRemoveAssignment = "update"; } if (!addUpdateRemoveAssignment.equals("remove") && gradeType == 3) { try { integrateGradebook(state, aReference, associateGradebookAssignment, addUpdateRemoveAssignment, aOldTitle, title, Integer.parseInt (gradePoints), dueTime, null, null); // add all existing grades, if any, into Gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update"); // if the assignment has been assoicated with a different entry in gradebook before, remove those grades from the entry in Gradebook if (StringUtil.trimToNull(oAssociateGradebookAssignment) != null && !oAssociateGradebookAssignment.equals(associateGradebookAssignment)) { // if the old assoicated assignment entry in GB is an external one, but doesn't have anything assoicated with it in Assignment tool, remove it removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,g, gradebookUid); } } catch (NumberFormatException nE) { alertInvalidPoint(state, gradePoints); } } else { integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null); } } } else { // need to remove the associated gradebook entry if 1) it is external and 2) no other assignment are associated with it removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,g, gradebookUid); } } } private void removeNonAssociatedExternalGradebookEntry(String context, String assignmentReference, String associateGradebookAssignment, GradebookService g, String gradebookUid) { boolean isExternalAssignmentDefined=g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment); if (isExternalAssignmentDefined) { // iterate through all assignments currently in the site, see if any is associated with this GB entry Iterator i = AssignmentService.getAssignmentsForContext(context); boolean found = false; while (!found && i.hasNext()) { Assignment aI = (Assignment) i.next(); String gbEntry = aI.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (aI.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED) == null && gbEntry != null && gbEntry.equals(associateGradebookAssignment) && !aI.getReference().equals(assignmentReference)) { found = true; } } // so if none of the assignment in this site is associated with the entry, remove the entry if (!found) { g.removeExternalAssessment(gradebookUid, associateGradebookAssignment); } } } private void integrateWithAnnouncement(SessionState state, String aOldTitle, AssignmentEdit a, String title, Time openTime, String checkAutoAnnounce, Time oldOpenTime) { if (checkAutoAnnounce.equalsIgnoreCase(Boolean.TRUE.toString())) { AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL); if (channel != null) { // whether the assignment's title or open date has been updated boolean updatedTitle = false; boolean updatedOpenDate = false; String openDateAnnounced = StringUtil.trimToNull(a.getProperties().getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED)); String openDateAnnouncementId = StringUtil.trimToNull(a.getPropertiesEdit().getProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID)); if (openDateAnnounced != null && openDateAnnouncementId != null) { try { AnnouncementMessage message = channel.getAnnouncementMessage(openDateAnnouncementId); if (!message.getAnnouncementHeader().getSubject().contains(title))/*whether title has been changed*/ { updatedTitle = true; } if (!message.getBody().contains(openTime.toStringLocalFull())) /*whether open date has been changed*/ { updatedOpenDate = true; } } catch (IdUnusedException e) { Log.warn("chef", e.getMessage()); } catch (PermissionException e) { Log.warn("chef", e.getMessage()); } } // need to create announcement message if assignment is added or assignment has been updated if (openDateAnnounced == null || updatedTitle || updatedOpenDate) { try { AnnouncementMessageEdit message = channel.addAnnouncementMessage(); AnnouncementMessageHeaderEdit header = message.getAnnouncementHeaderEdit(); header.setDraft(/* draft */false); header.replaceAttachments(/* attachment */EntityManager.newReferenceList()); if (openDateAnnounced == null) { // making new announcement header.setSubject(/* subject */rb.getString("assig6") + " " + title); } else { // updated title header.setSubject(/* subject */rb.getString("assig5") + " " + title); } if (updatedOpenDate) { // revised assignment open date message.setBody(/* body */rb.getString("newope") + " " + FormattedText.convertPlaintextToFormattedText(title) + " " + rb.getString("is") + " " + openTime.toStringLocalFull() + ". "); } else { // assignment open date message.setBody(/* body */rb.getString("opedat") + " " + FormattedText.convertPlaintextToFormattedText(title) + " " + rb.getString("is") + " " + openTime.toStringLocalFull() + ". "); } // group information if (a.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { try { // get the group ids selected Collection groupRefs = a.getGroups(); // make a collection of Group objects Collection groups = new Vector(); //make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); groups.add(site.getGroup(groupRef)); } // set access header.setGroupAccess(groups); } catch (Exception exception) { // log Log.warn("chef", exception.getMessage()); } } else { // site announcement header.clearGroupAccess(); } channel.commitMessage(message, NotificationService.NOTI_NONE); // commit related properties into Assignment object String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); aEdit.getPropertiesEdit().addProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED, Boolean.TRUE.toString()); if (message != null) { aEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID, message.getId()); } AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotmak")); } } } } // if } private void integrateWithCalendar(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit) { Calendar c = (Calendar) state.getAttribute(CALENDAR); if (c != null) { String dueDateScheduled = a.getProperties().getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); String oldEventId = aPropertiesEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); CalendarEvent e = null; if (dueDateScheduled != null || oldEventId != null) { // find the old event boolean found = false; if (oldEventId != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { Log.warn("chef", "The old event has been deleted: event id=" + oldEventId + ". "); } catch (PermissionException ee) { Log.warn("chef", "You do not have the permission to view the schedule event id= " + oldEventId + "."); } } else { TimeBreakdown b = oldDueTime.breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); try { Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null) .iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1) { found = true; } } } catch (PermissionException ignore) { // ignore PermissionException } } if (found) { // remove the founded old event try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotrem") + " " + title + ". "); } catch (InUseException ee) { Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen")); } catch (IdUnusedException ee) { Log.warn("chef", rb.getString("cannotfin6") + e.getId()); } } } if (checkAddDueTime.equalsIgnoreCase(Boolean.TRUE.toString())) { // commit related properties into Assignment object String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); try { e = null; CalendarEvent.EventAccess eAccess = CalendarEvent.EventAccess.SITE; Collection eGroups = new Vector(); if (aEdit.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { eAccess = CalendarEvent.EventAccess.GROUPED; Collection groupRefs = aEdit.getGroups(); // make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); eGroups.add(site.getGroup(groupRef)); } } e = c.addEvent(/* TimeRange */TimeService.newTimeRange(dueTime.getTime(), /* 0 duration */0 * 60 * 1000), /* title */rb.getString("due") + " " + title, /* description */rb.getString("assig1") + " " + title + " " + "is due on " + dueTime.toStringLocalFull() + ". ", /* type */rb.getString("deadl"), /* location */"", /* access */ eAccess, /* groups */ eGroups, /* attachments */EntityManager.newReferenceList()); aEdit.getProperties().addProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED, Boolean.TRUE.toString()); if (e != null) { aEdit.getProperties().addProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID, e.getId()); } // edit the calendar ojbject and add an assignment id field CalendarEventEdit edit = c.getEditEvent(e.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_ADD_CALENDAR); edit.setField(NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID, a.getId()); c.commitEvent(edit); } catch (IdUnusedException ee) { Log.warn("chef", ee.getMessage()); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotfin1")); } catch (Exception ee) { Log.warn("chef", ee.getMessage()); } // try-catch AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } } // if } } private void commitAssignmentEdit(SessionState state, boolean post, AssignmentContentEdit ac, AssignmentEdit a, String title, Time openTime, Time dueTime, Time closeTime, boolean enableCloseDate, String s, String range, Collection groups) { a.setTitle(title); a.setContent(ac); a.setContext((String) state.getAttribute(STATE_CONTEXT_STRING)); a.setSection(s); a.setOpenTime(openTime); a.setDueTime(dueTime); // set the drop dead date as the due date a.setDropDeadTime(dueTime); if (enableCloseDate) { a.setCloseTime(closeTime); } else { // if editing an old assignment with close date if (a.getCloseTime() != null) { a.setCloseTime(null); } } // post the assignment a.setDraft(!post); try { if (range.equals("site")) { a.setAccess(Assignment.AssignmentAccess.SITE); a.clearGroupAccess(); } else if (range.equals("groups")) { a.setGroupAccess(groups); } } catch (PermissionException e) { addAlert(state, rb.getString("youarenot1")); } if (state.getAttribute(STATE_MESSAGE) == null) { // commit assignment first AssignmentService.commitEdit(a); } } private void editAssignmentProperties(AssignmentEdit a, String checkAddDueTime, String checkAutoAnnounce, String addtoGradebook, String associateGradebookAssignment, String allowResubmitNumber, ResourcePropertiesEdit aPropertiesEdit, boolean post) { if (aPropertiesEdit.getProperty("newAssignment") != null) { if (aPropertiesEdit.getProperty("newAssignment").equalsIgnoreCase(Boolean.TRUE.toString())) { // not a newly created assignment, been added. aPropertiesEdit.addProperty("newAssignment", Boolean.FALSE.toString()); } } else { // for newly created assignment aPropertiesEdit.addProperty("newAssignment", Boolean.TRUE.toString()); } if (checkAddDueTime != null) { aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, checkAddDueTime); } else { aPropertiesEdit.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, checkAutoAnnounce); aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, addtoGradebook); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateGradebookAssignment); if (post && addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { // if the choice is to add an entry into Gradebook, let just mark it as associated with such new entry then aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, a.getReference()); } // allow resubmit number if (allowResubmitNumber != null) { aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } } private void commitAssignmentContentEdit(SessionState state, AssignmentContentEdit ac, String title, int submissionType,boolean useReviewService, boolean allowStudentViewReport, int gradeType, String gradePoints, String description, String checkAddHonorPledge, List attachments1) { ac.setTitle(title); ac.setInstructions(description); ac.setHonorPledge(Integer.parseInt(checkAddHonorPledge)); ac.setTypeOfSubmission(submissionType); ac.setAllowReviewService(useReviewService); ac.setAllowStudentViewReport(allowStudentViewReport); ac.setTypeOfGrade(gradeType); if (gradeType == 3) { try { ac.setMaxGradePoint(Integer.parseInt(gradePoints)); } catch (NumberFormatException e) { alertInvalidPoint(state, gradePoints); } } ac.setGroupProject(true); ac.setIndividuallyGraded(false); if (submissionType != 1) { ac.setAllowAttachments(true); } else { ac.setAllowAttachments(false); } // clear attachments ac.clearAttachments(); // add each attachment Iterator it = EntityManager.newReferenceList(attachments1).iterator(); while (it.hasNext()) { Reference r = (Reference) it.next(); ac.addAttachment(r); } state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false)); // commit the changes AssignmentService.commitEdit(ac); } /** * reorderAssignments */ private void reorderAssignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List assignments = prepPage(state); Iterator it = assignments.iterator(); // temporarily allow the user to read and write from assignments (asn.revise permission) SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); while (it.hasNext()) // reads and writes the parameter for default ordering { Assignment a = (Assignment) it.next(); String assignmentid = a.getId(); String assignmentposition = params.getString("position_" + assignmentid); AssignmentEdit ae = getAssignmentEdit(state, assignmentid); ae.setPosition_order(new Long(assignmentposition).intValue()); AssignmentService.commitEdit(ae); } // clear the permission SecurityService.clearAdvisors(); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); //resetAssignment(state); } } // reorderAssignments private AssignmentEdit getAssignmentEdit(SessionState state, String assignmentId) { AssignmentEdit a = null; if (assignmentId.length() == 0) { // create a new assignment try { a = AssignmentService.addAssignment((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot1")); } } else { try { // edit assignment a = AssignmentService.editAssignment(assignmentId); } catch (InUseException e) { addAlert(state, rb.getString("theassicon")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } // try-catch } // if-else return a; } private AssignmentContentEdit getAssignmentContentEdit(SessionState state, String assignmentContentId) { AssignmentContentEdit ac = null; if (assignmentContentId.length() == 0) { // new assignment try { ac = AssignmentService.addAssignmentContent((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot3")); } } else { try { // edit assignment ac = AssignmentService.editAssignmentContent(assignmentContentId); } catch (InUseException e) { addAlert(state, rb.getString("theassicon")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin4")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot15")); } } return ac; } private Time getOpenTime(SessionState state) { int openMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMONTH)).intValue(); int openDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENDAY)).intValue(); int openYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENYEAR)).intValue(); int openHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENHOUR)).intValue(); int openMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMIN)).intValue(); String openAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_OPENAMPM); if ((openAMPM.equals("PM")) && (openHour != 12)) { openHour = openHour + 12; } if ((openHour == 12) && (openAMPM.equals("AM"))) { openHour = 0; } Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0); return openTime; } private Time getCloseTime(SessionState state) { Time closeTime; int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); return closeTime; } private Time getDueTime(SessionState state) { int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue(); int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue(); int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue(); int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue(); int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue(); String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); return dueTime; } private Time getAllowSubmitCloseTime(SessionState state) { int closeMonth = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(ALLOW_RESUBMIT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); return closeTime; } /** * Action is to post new assignment */ public void doSave_assignment(RunData data) { postOrSaveAssignment(data, "save"); } // doSave_assignment /** * Action is to reorder assignments */ public void doReorder_assignment(RunData data) { reorderAssignments(data); } // doReorder_assignments /** * Action is to preview the selected assignment */ public void doPreview_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); setNewAssignmentParameters(data, false); String assignmentId = data.getParameters().getString("assignmentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID, assignmentId); String assignmentContentId = data.getParameters().getString("assignmentContentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID, assignmentContentId); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false)); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT); } } // doPreview_assignment /** * Action is to view the selected assignment */ public void doView_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // show the assignment portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false)); // show the student view portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true)); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_ASSIGNMENT); } } // doView_Assignment /** * Action is for student to view one assignment content */ public void doView_assignment_as_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_ASSIGNMENT); } } // doView_assignment_as_student /** * Action is to show the edit assignment screen */ public void doEdit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = StringUtil.trimToNull(params.getString("assignmentId")); // whether the user can modify the assignment state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); // for the non_electronice assignment, submissions are auto-generated by the time that assignment is created; // don't need to go through the following checkings. if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { Iterator submissions = AssignmentService.getSubmissions(a).iterator(); if (submissions.hasNext()) { // any submitted? boolean anySubmitted = false; for (;submissions.hasNext() && !anySubmitted;) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getSubmitted() && s.getTimeSubmitted() != null) { anySubmitted = true; } } // any draft submission boolean anyDraft = false; for (;submissions.hasNext() && !anyDraft;) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (!s.getSubmitted()) { anyDraft = true; } } if (anySubmitted) { // if there is any submitted submission to this assignment, show alert addAlert(state, rb.getString("assig1") + " " + a.getTitle() + " " + rb.getString("hassum")); } if (anyDraft) { // otherwise, show alert about someone has started working on the assignment, not necessarily submitted addAlert(state, rb.getString("hasDraftSum")); } } } // SECTION MOD state.setAttribute(STATE_SECTION_STRING, a.getSection()); // put the names and values into vm file state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle()); state.setAttribute(NEW_ASSIGNMENT_ORDER, a.getPosition_order()); TimeBreakdown openTime = a.getOpenTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openTime.getYear())); int openHour = openTime.getHour(); if (openHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "AM"); } if (openHour == 0) { // for midnight point, we mark it as 12AM openHour = 12; } state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer((openHour > 12) ? openHour - 12 : openHour)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openTime.getMin())); TimeBreakdown dueTime = a.getDueTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueTime.getYear())); int dueHour = dueTime.getHour(); if (dueHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "AM"); } if (dueHour == 0) { // for midnight point, we mark it as 12AM dueHour = 12; } state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer((dueHour > 12) ? dueHour - 12 : dueHour)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueTime.getMin())); // generate alert when editing an assignment past due date if (a.getDueTime().before(TimeService.newTime())) { addAlert(state, rb.getString("youarenot17")); } if (a.getCloseTime() != null) { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); TimeBreakdown closeTime = a.getCloseTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeTime.getYear())); int closeHour = closeTime.getHour(); if (closeHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "AM"); } if (closeHour == 0) { // for the midnight point, we mark it as 12 AM closeHour = 12; } state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer((closeHour > 12) ? closeHour - 12 : closeHour)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeTime.getMin())); } else { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, state.getAttribute(NEW_ASSIGNMENT_DUEAMPM)); } state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection()); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(a.getContent().getTypeOfSubmission())); int typeOfGrade = a.getContent().getTypeOfGrade(); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(typeOfGrade)); if (typeOfGrade == 3) { state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay()); } state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions()); ResourceProperties properties = a.getProperties(); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, Integer.toString(a.getContent().getHonorPledge())); state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); state.setAttribute(ATTACHMENTS, a.getContent().getAttachments()); // notification option if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // group setting if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { state.setAttribute(NEW_ASSIGNMENT_RANGE, "site"); } else { state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups"); } state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):"0"); // set whether we use the review service or not state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, new Boolean(a.getContent().getAllowReviewService()).toString()); //set whether students can view the review service results state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, new Boolean(a.getContent().getAllowStudentViewReport()).toString()); state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups()); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doEdit_Assignment /** * Action is to show the delete assigment confirmation screen */ public void doDelete_confirm_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String[] assignmentIds = params.getStrings("selectedAssignments"); if (assignmentIds != null) { Vector ids = new Vector(); for (int i = 0; i < assignmentIds.length; i++) { String id = (String) assignmentIds[i]; if (!AssignmentService.allowRemoveAssignment(id)) { addAlert(state, rb.getString("youarenot9") + " " + id + ". "); } ids.add(id); } if (state.getAttribute(STATE_MESSAGE) == null) { // can remove all the selected assignments state.setAttribute(DELETE_ASSIGNMENT_IDS, ids); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DELETE_ASSIGNMENT); } } else { addAlert(state, rb.getString("youmust6")); } } // doDelete_confirm_Assignment /** * Action is to delete the confirmed assignments */ public void doDelete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String assignmentId = (String) ids.get(i); try { AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit(); String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String title = aEdit.getTitle(); // remove releted event if there is one String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString())) { removeCalendarEvent(state, aEdit, pEdit, title); } // if-else if (aEdit.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // if this is non-electronic submission, remove all the submissions List submissions = AssignmentService.getSubmissions(aEdit); if (submissions != null) { for (Iterator sIterator=submissions.iterator(); sIterator.hasNext();) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); try { AssignmentService.removeSubmission(AssignmentService.editSubmission((s.getReference()))); } catch (Exception eee) { addAlert(state, rb.getString("youarenot11_s") + " " + s.getReference() + ". "); } } } try { // remove the assignment content AssignmentService.removeAssignmentContent(AssignmentService.editAssignmentContent(aEdit.getContent().getReference())); } catch (Exception eee) { addAlert(state, rb.getString("youarenot11_c") + " " + aEdit.getContentReference() + ". "); } try { // remove the assignment afterwards AssignmentService.removeAssignment(aEdit); } catch (Exception ee) { addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". "); } } else { // for assignment with other type of submission if (!AssignmentService.getSubmissions(aEdit).iterator().hasNext()) { // there is no submission to this assignment yet, delete the assignment and assignment content record completely try { // remove the assignment content AssignmentService.removeAssignmentContent(AssignmentService.editAssignmentContent(aEdit.getContent().getReference())); } catch (Exception ee) { addAlert(state, rb.getString("youarenot11_c") + " " + aEdit.getContentReference() + ". "); } try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(aEdit)); } } AssignmentService.removeAssignment(aEdit); } catch (PermissionException ee) { addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". "); } } else { // remove the assignment by marking the remove status property true pEdit.addProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED, Boolean.TRUE.toString()); AssignmentService.commitEdit(aEdit); } } // remove from Gradebook integrateGradebook(state, (String) ids.get (i), associateGradebookAssignment, "remove", null, null, -1, null, null, null); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot6")); } } // for if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset paging information after the assignment been deleted resetPaging(state); } } // doDelete_Assignment private void removeCalendarEvent(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title) throws PermissionException { // remove the associated calender event Calendar c = (Calendar) state.getAttribute(CALENDAR); if (c != null) { // already has calendar object // get the old event CalendarEvent e = null; boolean found = false; String oldEventId = pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); if (oldEventId != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { // no action needed for this condition } catch (PermissionException ee) { } } else { TimeBreakdown b = aEdit.getDueTime().breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null).iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1) { found = true; } } } // remove the founded old event if (found) { // found the old event delete it try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); pEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); pEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotrem") + " " + title + ". "); } catch (InUseException ee) { Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen")); } catch (IdUnusedException ee) { Log.warn("chef", rb.getString("cannotfin6") + e.getId()); } } } } /** * Action is to delete the assignment and also the related AssignmentSubmission */ public void doDeep_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String currentId = (String) ids.get(i); try { AssignmentEdit a = AssignmentService.editAssignment(currentId); try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(a)); } } AssignmentService.removeAssignment(a); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot11") + " " + a.getTitle() + ". "); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2")); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doDeep_delete_Assignment /** * Action is to show the duplicate assignment screen */ public void doDuplicate_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the view, so start with first page again. resetPaging(state); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); ParameterParser params = data.getParameters(); String assignmentId = StringUtil.trimToNull(params.getString("assignmentId")); if (assignmentId != null) { try { AssignmentEdit aEdit = AssignmentService.addDuplicateAssignment(contextString, assignmentId); // clean the duplicate's property ResourcePropertiesEdit aPropertiesEdit = aEdit.getPropertiesEdit(); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID); AssignmentService.commitEdit(aEdit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot5")); } catch (IdInvalidException e) { addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("isnotval")); } catch (IdUnusedException e) { addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("hasnotbee")); } catch (Exception e) { } } } // doDuplicate_Assignment /** * Action is to show the grade submission screen */ public void doGrade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); // reset the grade assignment id state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID, params.getString("assignmentId")); state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, params.getString("submissionId")); // allow resubmit number String allowResubmitNumber = "0"; Assignment a = null; try { a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { allowResubmitNumber= a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } try { AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)); if ((s.getFeedbackText() == null) || (s.getFeedbackText().length() == 0)) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText()); } else { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getFeedbackText()); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, s.getFeedbackComment()); List v = EntityManager.newReferenceList(); Iterator attachments = s.getFeedbackAttachments().iterator(); while (attachments.hasNext()) { v.add(attachments.next()); } state.setAttribute(ATTACHMENTS, v); state.setAttribute(GRADE_SUBMISSION_GRADE, s.getGrade()); ResourceProperties p = s.getProperties(); if (p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { allowResubmitNumber = p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } else if (p.getProperty(GRADE_SUBMISSION_ALLOW_RESUBMIT) != null) { // if there is any legacy setting for generally allow resubmit, set the allow resubmit number to be 1, and remove the legacy property allowResubmitNumber = "1"; } state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } } // doGrade_submission /** * Action is to release all the grades of the submission */ public void doRelease_grades(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); try { // get the assignment Assignment a = AssignmentService.getAssignment(params.getString("assignmentId")); String aReference = a.getReference(); Iterator submissions = AssignmentService.getSubmissions(a).iterator(); while (submissions.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getGraded()) { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference()); String grade = s.getGrade(); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)) .booleanValue() : false; if (withGrade) { // for the assignment tool with grade option, a valide grade is needed if (grade != null && !grade.equals("")) { sEdit.setGradeReleased(true); } } else { // for the assignment tool without grade option, no grade is needed sEdit.setGradeReleased(true); } // also set the return status sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); AssignmentService.commitEdit(sEdit); } } // while // add grades into Gradebook String integrateWithGradebook = a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); if (integrateWithGradebook != null && !integrateWithGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // integrate with Gradebook String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update"); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } // doRelease_grades /** * Action is to show the assignment in grading page */ public void doExpand_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(true)); } // doExpand_grade_assignment /** * Action is to hide the assignment in grading page */ public void doCollapse_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); } // doCollapse_grade_assignment /** * Action is to show the submissions in grading page */ public void doExpand_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true)); } // doExpand_grade_submission /** * Action is to hide the submissions in grading page */ public void doCollapse_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(false)); } // doCollapse_grade_submission /** * Action is to show the grade assignment */ public void doGrade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // clean state attribute state.removeAttribute(USER_SUBMISSIONS); state.setAttribute(EXPORT_ASSIGNMENT_REF, params.getString("assignmentId")); try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); // we are changing the view, so start with first page again. resetPaging(state); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } // doGrade_assignment /** * Action is to show the View Students assignment screen */ public void doView_students_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } // doView_students_Assignment /** * Action is to show the student submissions */ public void doShow_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // add the student id into the table t.add(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doShow_student_submission /** * Action is to hide the student submissions */ public void doHide_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // remove the student id from the table t.remove(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doHide_student_submission /** * Action is to show the graded assignment submission */ public void doView_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId")); state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE); } // doView_grade /** * Action is to show the student submissions */ public void doReport_submissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REPORT_SUBMISSIONS); state.setAttribute(SORTED_BY, SORTED_SUBMISSION_BY_LASTNAME); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doReport_submissions /** * * */ public void doAssignment_form(RunData data) { ParameterParser params = data.getParameters(); String option = (String) params.getString("option"); if (option != null) { if (option.equals("post")) { // post assignment doPost_assignment(data); } else if (option.equals("save")) { // save assignment doSave_assignment(data); } else if (option.equals("reorder")) { // reorder assignments doReorder_assignment(data); } else if (option.equals("preview")) { // preview assignment doPreview_assignment(data); } else if (option.equals("cancel")) { // cancel creating assignment doCancel_new_assignment(data); } else if (option.equals("canceledit")) { // cancel editing assignment doCancel_edit_assignment(data); } else if (option.equals("attach")) { // attachments doAttachments(data); } else if (option.equals("view")) { // view doView(data); } else if (option.equals("permissions")) { // permissions doPermissions(data); } else if (option.equals("returngrade")) { // return grading doReturn_grade_submission(data); } else if (option.equals("savegrade")) { // save grading doSave_grade_submission(data); } else if (option.equals("previewgrade")) { // preview grading doPreview_grade_submission(data); } else if (option.equals("cancelgrade")) { // cancel grading doCancel_grade_submission(data); } else if (option.equals("cancelreorder")) { // cancel reordering doCancel_reorder(data); } else if (option.equals("sortbygrouptitle")) { // read input data setNewAssignmentParameters(data, true); // sort by group title doSortbygrouptitle(data); } else if (option.equals("sortbygroupdescription")) { // read input data setNewAssignmentParameters(data, true); // sort group by description doSortbygroupdescription(data); } else if (option.equals("hide_instruction")) { // hide the assignment instruction doHide_submission_assignment_instruction(data); } else if (option.equals("show_instruction")) { // show the assignment instruction doShow_submission_assignment_instruction(data); } else if (option.equals("sortbygroupdescription")) { // show the assignment instruction doShow_submission_assignment_instruction(data); } else if (option.equals("revise") || option.equals("done")) { // back from the preview mode doDone_preview_new_assignment(data); } } } /** * Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked */ public void doAttachments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String mode = (String) state.getAttribute(STATE_MODE); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { setNewAssignmentParameters(data, false); } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { readGradeForm(data, state, "read"); } if (state.getAttribute(STATE_MESSAGE) == null) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.filepicker"); state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig")); state.setAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT, rb.getString("gen.addatttoassiginstr")); // use the real attachment list state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); } } /** * readGradeForm */ public void readGradeForm(RunData data, SessionState state, String gradeOption) { ParameterParser params = data.getParameters(); int typeOfGrade = -1; boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue() : false; boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT), checkForFormattingErrors); if (feedbackComment != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment); } String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT)); if (feedbackText != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS)); String g = params.getCleanString(GRADE_SUBMISSION_GRADE); if (g != null) { state.setAttribute(GRADE_SUBMISSION_GRADE, g); } String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); try { // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); Assignment a = AssignmentService.getSubmission(sId).getAssignment(); typeOfGrade = a.getContent().getTypeOfGrade(); if (withGrade) { // do grade validation only for Assignment with Grade tool if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { if ((grade.length() == 0)) { state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } else { // the preview grade process might already scaled up the grade by 10 if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } } // if ungraded and grade type is not "ungraded" type if ((grade == null || grade.equals("ungraded")) && (typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) && gradeOption.equals("release")) { addAlert(state, rb.getString("plespethe2")); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // allow resubmit number and due time if (params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { String allowResubmitNumberString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (Integer.parseInt(allowResubmitNumberString) != 0) { int closeMonth = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMONTH))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, new Integer(closeMonth)); int closeDay = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEDAY))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, new Integer(closeDay)); int closeYear = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEYEAR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, new Integer(closeYear)); int closeHour = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEHOUR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, new Integer(closeHour)); int closeMin = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMIN))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, new Integer(closeMin)); String closeAMPM = params.getString(ALLOW_RESUBMIT_CLOSEAMPM); state.setAttribute(ALLOW_RESUBMIT_CLOSEAMPM, closeAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); // validate date if (closeTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) == null) { state.setAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE, Boolean.TRUE); } else { // clean the attribute after user confirm state.removeAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE); } if (state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) != null) { addAlert(state, rb.getString("acesubdea4")); } if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + "."); } } else { // reset the state attributes state.removeAttribute(ALLOW_RESUBMIT_CLOSEMONTH); state.removeAttribute(ALLOW_RESUBMIT_CLOSEDAY); state.removeAttribute(ALLOW_RESUBMIT_CLOSEYEAR); state.removeAttribute(ALLOW_RESUBMIT_CLOSEHOUR); state.removeAttribute(ALLOW_RESUBMIT_CLOSEMIN); state.removeAttribute(ALLOW_RESUBMIT_CLOSEAMPM); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } if (state.getAttribute(STATE_MESSAGE) == null) { String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); grade = (typeOfGrade == Assignment.SCORE_GRADE_TYPE)?scalePointGrade(state, grade):grade; state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } /** * Populate the state object, if needed - override to do something! */ protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data) { super.initState(state, portlet, data); if (m_contentHostingService == null) { m_contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); } String siteId = ToolManager.getCurrentPlacement().getContext(); // show the list of assignment view first if (state.getAttribute(STATE_SELECTED_VIEW) == null) { state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_USER) == null) { state.setAttribute(STATE_USER, UserDirectoryService.getCurrentUser()); } /** The content type image lookup service in the State. */ ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); if (iService == null) { iService = org.sakaiproject.content.cover.ContentTypeImageService.getInstance(); state.setAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE, iService); } // if /** The calendar tool */ if (state.getAttribute(CALENDAR_TOOL_EXIST) == null) { if (!siteHasTool(siteId, "sakai.schedule")) { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.FALSE); state.removeAttribute(CALENDAR); } else { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE); if (state.getAttribute(CALENDAR) == null ) { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE); CalendarService cService = org.sakaiproject.calendar.cover.CalendarService.getInstance(); state.setAttribute(STATE_CALENDAR_SERVICE, cService); String calendarId = ServerConfigurationService.getString("calendar", null); if (calendarId == null) { calendarId = cService.calendarReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(CALENDAR, cService.getCalendar(calendarId)); } catch (IdUnusedException e) { Log.info("chef", "No calendar found for site " + siteId); state.removeAttribute(CALENDAR); } catch (PermissionException e) { Log.info("chef", "No permission to get the calender. "); state.removeAttribute(CALENDAR); } catch (Exception ex) { Log.info("chef", "Assignment : Action : init state : calendar exception : " + ex); state.removeAttribute(CALENDAR); } } } } } /** The Announcement tool */ if (state.getAttribute(ANNOUNCEMENT_TOOL_EXIST) == null) { if (!siteHasTool(siteId, "sakai.announcements")) { state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.FALSE); state.removeAttribute(ANNOUNCEMENT_CHANNEL); } else { state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.TRUE); if (state.getAttribute(ANNOUNCEMENT_CHANNEL) == null ) { /** The announcement service in the State. */ AnnouncementService aService = (AnnouncementService) state.getAttribute(STATE_ANNOUNCEMENT_SERVICE); if (aService == null) { aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance(); state.setAttribute(STATE_ANNOUNCEMENT_SERVICE, aService); String channelId = ServerConfigurationService.getString("channel", null); if (channelId == null) { channelId = aService.channelReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(ANNOUNCEMENT_CHANNEL, aService.getAnnouncementChannel(channelId)); } catch (IdUnusedException e) { Log.warn("chef", "No announcement channel found. "); state.removeAttribute(ANNOUNCEMENT_CHANNEL); } catch (PermissionException e) { Log.warn("chef", "No permission to annoucement channel. "); } catch (Exception ex) { Log.warn("chef", "Assignment : Action : init state : calendar exception : " + ex); } } } } } } // if if (state.getAttribute(STATE_CONTEXT_STRING) == null) { state.setAttribute(STATE_CONTEXT_STRING, siteId); } // if context string is null if (state.getAttribute(SORTED_BY) == null) { setDefaultSort(state); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_BY) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, SORTED_GRADE_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(SORTED_SUBMISSION_BY) == null) { state.setAttribute(SORTED_SUBMISSION_BY, SORTED_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG) == null) { resetAssignment(state); } if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) == null) { state.setAttribute(STUDENT_LIST_SHOW_TABLE, new HashSet()); } if (state.getAttribute(ATTACHMENTS_MODIFIED) == null) { state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false)); } // SECTION MOD if (state.getAttribute(STATE_SECTION_STRING) == null) { state.setAttribute(STATE_SECTION_STRING, "001"); } // // setup the observer to notify the Main panel // if (state.getAttribute(STATE_OBSERVER) == null) // { // // the delivery location for this tool // String deliveryId = clientWindowId(state, portlet.getID()); // // // the html element to update on delivery // String elementId = mainPanelUpdateId(portlet.getID()); // // // the event resource reference pattern to watch for // String pattern = AssignmentService.assignmentReference((String) state.getAttribute (STATE_CONTEXT_STRING), ""); // // state.setAttribute(STATE_OBSERVER, new MultipleEventsObservingCourier(deliveryId, elementId, pattern)); // } if (state.getAttribute(STATE_MODE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) { state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0)); } if (state.getAttribute(WITH_GRADES) == null) { PortletConfig config = portlet.getPortletConfig(); String withGrades = StringUtil.trimToNull(config.getInitParameter("withGrades")); if (withGrades == null) { withGrades = Boolean.FALSE.toString(); } state.setAttribute(WITH_GRADES, new Boolean(withGrades)); } // whether the choice of emails instructor submission notification is available in the installation if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) == null) { state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, Boolean.valueOf(ServerConfigurationService.getBoolean(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, true))); } // whether or how the instructor receive submission notification emails, none(default)|each|digest if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT) == null) { state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, ServerConfigurationService.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE)); } if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM) == null) { state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM, new Integer(2002)); } if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO) == null) { state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO, new Integer(2012)); } } // initState /** * whether the site has the specified tool * @param siteId * @return */ private boolean siteHasTool(String siteId, String toolId) { boolean rv = false; try { Site s = SiteService.getSite(siteId); if (s.getToolForCommonId(toolId) != null) { rv = true; } } catch (Exception e) { Log.info("chef", this + e.getMessage() + siteId); } return rv; } /** * reset the attributes for view submission */ private void resetViewSubmission(SessionState state) { state.removeAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); state.removeAttribute(VIEW_SUBMISSION_TEXT); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } // resetViewSubmission /** * reset the attributes for view submission */ private void resetAssignment(SessionState state) { // put the input value into the state attributes state.setAttribute(NEW_ASSIGNMENT_TITLE, ""); // get current time Time t = TimeService.newTime(); TimeBreakdown tB = t.breakdownLocal(); int month = tB.getMonth(); int day = tB.getDay(); int year = tB.getYear(); // set the open time to be 12:00 PM state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(12)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM"); // due date is shifted forward by 7 days t.setTime(t.getTime() + 7 * 24 * 60 * 60 * 1000); tB = t.breakdownLocal(); month = tB.getMonth(); day = tB.getDay(); year = tB.getYear(); // set the due time to be 5:00pm state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(5)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM"); // enable the close date by default state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); // set the close time to be 5:00 pm, same as the due time by default state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(5)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM"); state.setAttribute(NEW_ASSIGNMENT_SECTION, "001"); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(Assignment.UNGRADED_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, ""); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, ""); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); // make the honor pledge not include as the default state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, (new Integer(Assignment.HONOR_PLEDGE_NONE)).toString()); state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, EntityManager.newReferenceList()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_TITLE); state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } state.removeAttribute(NEW_ASSIGNMENT_RANGE); state.removeAttribute(NEW_ASSIGNMENT_GROUPS); // remove the edit assignment id if any state.removeAttribute(EDIT_ASSIGNMENT_ID); // remove the resubmit number state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } // resetNewAssignment /** * construct a Hashtable using integer as the key and three character string of the month as the value */ private Hashtable monthTable() { Hashtable n = new Hashtable(); n.put(new Integer(1), rb.getString("jan")); n.put(new Integer(2), rb.getString("feb")); n.put(new Integer(3), rb.getString("mar")); n.put(new Integer(4), rb.getString("apr")); n.put(new Integer(5), rb.getString("may")); n.put(new Integer(6), rb.getString("jun")); n.put(new Integer(7), rb.getString("jul")); n.put(new Integer(8), rb.getString("aug")); n.put(new Integer(9), rb.getString("sep")); n.put(new Integer(10), rb.getString("oct")); n.put(new Integer(11), rb.getString("nov")); n.put(new Integer(12), rb.getString("dec")); return n; } // monthTable /** * construct a Hashtable using the integer as the key and grade type String as the value */ private Hashtable gradeTypeTable() { Hashtable n = new Hashtable(); n.put(new Integer(2), rb.getString("letter")); n.put(new Integer(3), rb.getString("points")); n.put(new Integer(4), rb.getString("pass")); n.put(new Integer(5), rb.getString("check")); n.put(new Integer(1), rb.getString("ungra")); return n; } // gradeTypeTable /** * construct a Hashtable using the integer as the key and submission type String as the value */ private Hashtable submissionTypeTable() { Hashtable n = new Hashtable(); n.put(new Integer(1), rb.getString("inlin")); n.put(new Integer(2), rb.getString("attaonly")); n.put(new Integer(3), rb.getString("inlinatt")); n.put(new Integer(4), rb.getString("nonelec")); return n; } // submissionTypeTable /** * Sort based on the given property */ public void doSort(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); setupSort(data, data.getParameters().getString("criteria")); } /** * setup sorting parameters * * @param criteria * String for sortedBy */ private void setupSort(RunData data, String criteria) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } } // doSort /** * Do sort by group title */ public void doSortbygrouptitle(RunData data) { setupSort(data, SORTED_BY_GROUP_TITLE); } // doSortbygrouptitle /** * Do sort by group description */ public void doSortbygroupdescription(RunData data) { setupSort(data, SORTED_BY_GROUP_DESCRIPTION); } // doSortbygroupdescription /** * Sort submission based on the given property */ public void doSort_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_SUBMISSION_BY))) { state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_SUBMISSION_ASC, asc); } } // doSort_submission /** * Sort submission based on the given property in instructor grade view */ public void doSort_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_GRADE_SUBMISSION_BY))) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); //for content review default is desc if (criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW)) asc = Boolean.FALSE.toString(); else asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } } // doSort_grade_submission public void doSort_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Sort sort = dtp.getSort(); if (sort.getSort().equals(criteria)) { sort.setAscending(sort.isAscending() ? false : true); } else { sort.setSort(criteria); sort.setAscending(true); } break; } } } public void doPage_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String page = params.getString("page"); String pageSize = params.getString("pageSize"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Pager pager = dtp.getPager(); pager.setPageSize(Integer.valueOf(pageSize)); if (Pager.FIRST.equals(page)) { pager.setFirstItem(0); } else if (Pager.PREVIOUS.equals(page)) { pager.setFirstItem(pager.getFirstItem() - pager.getPageSize()); } else if (Pager.NEXT.equals(page)) { pager.setFirstItem(pager.getFirstItem() + pager.getPageSize()); } else if (Pager.LAST.equals(page)) { pager.setFirstItem((pager.getTotalItems() / pager .getPageSize()) * pager.getPageSize()); } break; } } } /** * the UserSubmission clas */ public class UserSubmission { /** * the User object */ User m_user = null; /** * the AssignmentSubmission object */ AssignmentSubmission m_submission = null; public UserSubmission(User u, AssignmentSubmission s) { m_user = u; m_submission = s; } /** * Returns the AssignmentSubmission object */ public AssignmentSubmission getSubmission() { return m_submission; } /** * Returns the User object */ public User getUser() { return m_user; } } /** * the AssignmentComparator clas */ private class AssignmentComparator implements Comparator { Collator collator = Collator.getInstance(); /** * the SessionState object */ SessionState m_state = null; /** * the criteria */ String m_criteria = null; /** * the criteria */ String m_asc = null; /** * the user */ User m_user = null; /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. */ public AssignmentComparator(SessionState state, String criteria, String asc) { m_state = state; m_criteria = criteria; m_asc = asc; } // constructor /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. * @param user * The user object */ public AssignmentComparator(SessionState state, String criteria, String asc, User user) { m_state = state; m_criteria = criteria; m_asc = asc; m_user = user; } // constructor /** * caculate the range string for an assignment */ private String getAssignmentRange(Assignment a) { String rv = ""; if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { // site assignment rv = rb.getString("range.allgroups"); } else { try { // get current site Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); for (Iterator k = a.getGroups().iterator(); k.hasNext();) { // announcement by group rv = rv.concat(site.getGroup((String) k.next()).getTitle()); } } catch (Exception ignore) { } } return rv; } // getAssignmentRange /** * implementing the compare function * * @param o1 * The first object * @param o2 * The second object * @return The compare result. 1 is o1 < o2; -1 otherwise */ public int compare(Object o1, Object o2) { int result = -1; if (m_criteria == null) { m_criteria = SORTED_BY_DEFAULT; } /** *********** for sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_DEFAULT)) { int s1 = ((Assignment) o1).getPosition_order(); int s2 = ((Assignment) o2).getPosition_order(); if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.equals(t2)) { t1 = ((Assignment) o1).getTimeCreated(); t2 = ((Assignment) o2).getTimeCreated(); } if (t1!=null && t2!=null && t1.before(t2)) { result = -1; } else { result = 1; } } else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list { result = 1; } else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom { result = -1; } else // 2 legitimate postion orders { result = (s1 < s2) ? -1 : 1; } } if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = compareString(s1, s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = compareString(s1, s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { result = compareString(((Assignment) o1).getStatus(), ((Assignment) o2).getStatus()); } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted()) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted()) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); result = compareString(submission1.getStatus(), submission2.getStatus()); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_GRADE)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = compareString(grade1, grade2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = compareString(maxGrade1, maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = compareString(factor1, factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = compareString(factor1, factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = compareString(factor1, factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW)) { UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null ) { result = 1; } else { int score1 = u1.getSubmission().getReviewScore(); int score2 = u2.getSubmission().getReviewScore(); result = (new Integer(score1)).intValue() > (new Integer(score2)).intValue() ? 1 : -1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { String lName1 = u1.getUser().getSortName(); String lName2 = u2.getUser().getSortName(); result = compareString(lName1, lName2); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = s1.getStatus(); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = s2.getStatus(); } } result = compareString(status1, status2); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (new Boolean(s1.getGradeReleased())).toString(); String released2 = (new Boolean(s2.getGradeReleased())).toString(); result = compareString(released1, released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name User[] u1 = ((AssignmentSubmission) o1).getSubmitters(); User[] u2 = ((AssignmentSubmission) o2).getSubmitters(); if (u1 == null || u2 == null) { return 1; } else { String submitters1 = ""; String submitters2 = ""; for (int j = 0; j < u1.length; j++) { if (u1[j] != null && u1[j].getSortName() != null) { if (j > 0) { submitters1 = submitters1.concat("; "); } submitters1 = submitters1.concat("" + u1[j].getSortName()); } } for (int j = 0; j < u2.length; j++) { if (u2[j] != null && u2[j].getSortName() != null) { if (j > 0) { submitters2 = submitters2.concat("; "); } submitters2 = submitters2.concat(u2[j].getSortName()); } } result = compareString(submitters1, submitters2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status result = compareString(((AssignmentSubmission) o1).getStatus(), ((AssignmentSubmission) o2).getStatus()); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = compareString(released1, released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = compareString(title1, title2); } /*************** sort user by sort name ***************/ else if (m_criteria.equals(SORTED_USER_BY_SORTNAME)) { // sort by user's sort name String name1 = ((User) o1).getSortName(); String name2 = ((User) o2).getSortName(); result = compareString(name1, name2); } // sort ascending or descending if (!Boolean.valueOf(m_asc)) { result = -result; } return result; } /** * Compare two strings as double values. Deal with the case when either of the strings cannot be parsed as double value. * @param grade1 * @param grade2 * @return */ private int compareDouble(String grade1, String grade2) { int result; try { result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1; } catch (Exception formatException) { // in case either grade1 or grade2 cannot be parsed as Double result = compareString(grade1, grade2); } return result; } // compareDouble private int compareString(String s1, String s2) { int result; if (s1 == null && s2 == null) { result = 0; } else if (s2 == null) { result = 1; } else if (s1 == null) { result = -1; } else { result = collator.compare(s1.toLowerCase(), s2.toLowerCase()); } return result; } /** * get submission status */ private String getSubmissionStatus(AssignmentSubmission submission, Assignment assignment) { String status = ""; if (submission != null) if (submission.getSubmitted()) if (submission.getGraded() && submission.getGradeReleased()) status = rb.getString("grad3"); else if (submission.getReturned()) status = rb.getString("return") + " " + submission.getTimeReturned().toStringLocalFull(); else { status = rb.getString("submitt") + submission.getTimeSubmitted().toStringLocalFull(); if (submission.getTimeSubmitted().after(assignment.getDueTime())) status = status + rb.getString("late"); } else status = rb.getString("inpro"); else status = rb.getString("notsta"); return status; } // getSubmissionStatus /** * get assignment maximun grade available based on the assignment grade type * * @param gradeType * The int value of grade type * @param a * The assignment object * @return The max grade String */ private String maxGrade(int gradeType, Assignment a) { String maxGrade = ""; if (gradeType == -1) { // Grade type not set maxGrade = rb.getString("granotset"); } else if (gradeType == 1) { // Ungraded grade type maxGrade = rb.getString("nogra"); } else if (gradeType == 2) { // Letter grade type maxGrade = "A"; } else if (gradeType == 3) { // Score based grade type maxGrade = Integer.toString(a.getContent().getMaxGradePoint()); } else if (gradeType == 4) { // Pass/fail grade type maxGrade = rb.getString("pass2"); } else if (gradeType == 5) { // Grade type that only requires a check maxGrade = rb.getString("check2"); } return maxGrade; } // maxGrade } // DiscussionComparator /** * Fire up the permissions editor */ public void doPermissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.permissions.helper"); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String siteRef = SiteService.siteReference(contextString); // setup for editing the permissions of the site for this tool, using the roles of this site, too state.setAttribute(PermissionsHelper.TARGET_REF, siteRef); // ... with this description state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " " + SiteService.getSiteDisplay(contextString)); // ... showing only locks that are prpefixed with this state.setAttribute(PermissionsHelper.PREFIX, "asn."); // disable auto-updates while leaving the list view justDelivered(state); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } // switching back to assignment list view state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); doList_assignments(data); } } // doPermissions /** * transforms the Iterator to Vector */ private Vector iterator_to_vector(Iterator l) { Vector v = new Vector(); while (l.hasNext()) { v.add(l.next()); } return v; } // iterator_to_vector /** * Implement this to return alist of all the resources that there are to page. Sort them as appropriate. */ protected List readResourcesPage(SessionState state, int first, int last) { List returnResources = (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS); PagingPosition page = new PagingPosition(first, last); page.validate(returnResources.size()); returnResources = returnResources.subList(page.getFirst() - 1, page.getLast()); return returnResources; } // readAllResources /* * (non-Javadoc) * * @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState) */ protected int sizeResources(SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // all the resources for paging List returnResources = new Vector(); boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); if (mode.equalsIgnoreCase(MODE_LIST_ASSIGNMENTS)) { String view = ""; if (state.getAttribute(STATE_SELECTED_VIEW) != null) { view = (String) state.getAttribute(STATE_SELECTED_VIEW); } if (allowAddAssignment && view.equals(MODE_LIST_ASSIGNMENTS)) { // read all Assignments returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (allowAddAssignment && view.equals(MODE_STUDENT_VIEW) || (!allowAddAssignment && AssignmentService.allowAddSubmission((String) state .getAttribute(STATE_CONTEXT_STRING)))) { // in the student list view of assignments Iterator assignments = AssignmentService .getAssignmentsForContext(contextString); Time currentTime = TimeService.newTime(); while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); try { String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if (deleted == null || deleted.equals("")) { // show not deleted assignments Time openTime = a.getOpenTime(); if (openTime != null && currentTime.after(openTime) && !a.getDraft()) { returnResources.add(a); } } else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) && AssignmentService.getSubmission(a.getReference(), (User) state .getAttribute(STATE_USER)) != null) { // and those deleted but not non-electronic assignments but the user has made submissions to them returnResources.add(a); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } } else { // read all Assignments returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } state.setAttribute(HAS_MULTIPLE_ASSIGNMENTS, Boolean.valueOf(returnResources.size() > 1)); } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REORDER_ASSIGNMENT)) { returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { Vector submissions = new Vector(); Vector assignments = iterator_to_vector(AssignmentService.getAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING))); if (assignments.size() > 0) { // users = AssignmentService.allowAddSubmissionUsers (((Assignment)assignments.get(0)).getReference ()); } for (int j = 0; j < assignments.size(); j++) { Assignment a = (Assignment) assignments.get(j); //get the list of users which are allowed to grade this assignment List allowGradeAssignmentUsers = AssignmentService.allowGradeAssignmentUsers(a.getReference()); String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if ((deleted == null || deleted.equals("")) && (!a.getDraft()) && AssignmentService.allowGradeSubmission(a.getReference())) { try { List assignmentSubmissions = AssignmentService.getSubmissions(a); for (int k = 0; k < assignmentSubmissions.size(); k++) { AssignmentSubmission s = (AssignmentSubmission) assignmentSubmissions.get(k); if (s != null && (s.getSubmitted() || (s.getReturned() && (s.getTimeLastModified().before(s .getTimeReturned()))))) { // has been subitted or has been returned and not work on it yet User[] submitters = s.getSubmitters(); if (!allowGradeAssignmentUsers.contains(submitters[0])) { // only include the student submission submissions.add(s); } } // if-else } } catch (Exception e) { } } } returnResources = submissions; } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT)) { // range Collection groups = new Vector(); try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); // all submissions List submissions = AssignmentService.getSubmissions(a); // now are we view all sections/groups or just specific one? String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); if (allOrOneGroup.equals(rb.getString("gen.viewallgroupssections"))) { if (AssignmentService.allowAllGroups(contextString)) { // site range groups.add(SiteService.getSite(contextString)); } else { // get all groups user can grade groups = AssignmentService.getGroupsAllowGradeAssignment(contextString, a.getReference()); } } else { // filter out only those submissions from the selected-group members try { Group group = SiteService.getSite(contextString).getGroup(allOrOneGroup); groups.add(group); } catch (Exception e) { Log.warn("chef", e.getMessage() + " groupId=" + allOrOneGroup); } } // all users that can submit List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); HashSet userIdSet = new HashSet(); for (Iterator iGroup=groups.iterator(); iGroup.hasNext();) { Object nGroup = iGroup.next(); String authzGroupRef = (nGroup instanceof Group)? ((Group) nGroup).getReference():((nGroup instanceof Site))?((Site) nGroup).getReference():null; if (authzGroupRef != null) { try { AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupRef); Set grants = group.getUsers(); for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); // don't show user multiple times if (!userIdSet.contains(userId)) { try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null && allowAddSubmissionUsers.contains(u)) { boolean found = false; for (int i = 0; !found && i<submissions.size();i++) { AssignmentSubmission s = (AssignmentSubmission) submissions.get(i); if (s.getSubmitterIds().contains(userId)) { returnResources.add(new UserSubmission(u, s)); found = true; } } // add those users who haven't made any submissions if (!found) { // construct fake submissions for grading purpose if the user has right for grading if (AssignmentService.allowGradeSubmission(a.getReference())) { // temporarily allow the user to read and write from assignments (asn.revise permission) SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); AssignmentSubmissionEdit s = AssignmentService.addSubmission(contextString, a.getId(), userId); s.setSubmitted(true); s.setAssignment(a); AssignmentService.commitEdit(s); // update the UserSubmission list by adding newly created Submission object AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference()); returnResources.add(new UserSubmission(u, sub)); // clear the permission SecurityService.clearAdvisors(); } } } } catch (Exception e) { Log.warn("chef", this + e.toString() + " here userId = " + userId); } // add userId into set to prevent showing user multiple times userIdSet.add(userId); } } } catch (Exception eee) { Log.warn("chef", eee.getMessage() + " authGroupId=" + authzGroupRef); } } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } // sort them all String ascending = "true"; String sort = ""; ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT) && (sort == null || !sort.startsWith("sorted_grade_submission_by"))) { ascending = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_BY); } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS) && (sort == null || sort.startsWith("sorted_submission_by"))) { ascending = (String) state.getAttribute(SORTED_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_SUBMISSION_BY); } else { ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); } if ((returnResources.size() > 1) && !mode.equalsIgnoreCase(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { Collections.sort(returnResources, new AssignmentComparator(state, sort, ascending)); } // record the total item number state.setAttribute(STATE_PAGEING_TOTAL_ITEMS, returnResources); return returnResources.size(); } public void doView(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); String viewMode = data.getParameters().getString("view"); state.setAttribute(STATE_SELECTED_VIEW, viewMode); if (viewMode.equals(MODE_LIST_ASSIGNMENTS)) { doList_assignments(data); } else if (viewMode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { doView_students_assignment(data); } else if (viewMode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { doReport_submissions(data); } else if (viewMode.equals(MODE_STUDENT_VIEW)) { doView_student(data); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } // doView /** * put those variables related to 2ndToolbar into context */ private void add2ndToolbarFields(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); context.put("selectedView", state.getAttribute(STATE_MODE)); } // add2ndToolbarFields /** * valid grade for point based type */ private void validPointGrade(SessionState state, String grade) { if (grade != null && !grade.equals("")) { if (grade.startsWith("-")) { // check for negative sign addAlert(state, rb.getString("plesuse3")); } else { int index = grade.indexOf("."); if (index != -1) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 if (!grade.equals(".")) { if (grade.length() > index + 2) { // if there are more than one decimal point addAlert(state, rb.getString("plesuse2")); } else { // decimal points is the only allowed character inside grade // replace it with '1', and try to parse the new String into int String gradeString = (grade.endsWith(".")) ? grade.substring(0, index).concat("0") : grade.substring(0, index).concat(grade.substring(index + 1)); try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { alertInvalidPoint(state, gradeString); } } } else { // grade is "." addAlert(state, rb.getString("plesuse1")); } } else { // There is no decimal point; should be int number String gradeString = grade + "0"; try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { alertInvalidPoint(state, gradeString); } } } } } // validPointGrade /** * valid grade for point based type */ private void validLetterGrade(SessionState state, String grade) { String VALID_CHARS_FOR_LETTER_GRADE = " ABCDEFGHIJKLMNOPQRSTUVWXYZ+-"; boolean invalid = false; if (grade != null) { grade = grade.toUpperCase(); for (int i = 0; i < grade.length() && !invalid; i++) { char c = grade.charAt(i); if (VALID_CHARS_FOR_LETTER_GRADE.indexOf(c) == -1) { invalid = true; } } if (invalid) { addAlert(state, rb.getString("plesuse0")); } } } private void alertInvalidPoint(SessionState state, String grade) { String VALID_CHARS_FOR_INT = "-01234567890"; boolean invalid = false; // case 1: contains invalid char for int for (int i = 0; i < grade.length() && !invalid; i++) { char c = grade.charAt(i); if (VALID_CHARS_FOR_INT.indexOf(c) == -1) { invalid = true; } } if (invalid) { addAlert(state, rb.getString("plesuse1")); } else { int maxInt = Integer.MAX_VALUE / 10; int maxDec = Integer.MAX_VALUE - maxInt * 10; // case 2: Due to our internal scaling, input String is larger than Integer.MAX_VALUE/10 addAlert(state, grade.substring(0, grade.length()-1) + "." + grade.substring(grade.length()-1) + " " + rb.getString("plesuse4") + maxInt + "." + maxDec + "."); } } /** * display grade properly */ private String displayGrade(SessionState state, String grade) { if (state.getAttribute(STATE_MESSAGE) == null) { if (grade != null && (grade.length() >= 1)) { if (grade.indexOf(".") != -1) { if (grade.startsWith(".")) { grade = "0".concat(grade); } else if (grade.endsWith(".")) { grade = grade.concat("0"); } } else { try { Integer.parseInt(grade); grade = grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1); } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } } else { grade = ""; } } return grade; } // displayGrade /** * scale the point value by 10 if there is a valid point grade */ private String scalePointGrade(SessionState state, String point) { validPointGrade(state, point); if (state.getAttribute(STATE_MESSAGE) == null) { if (point != null && (point.length() >= 1)) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 int index = point.indexOf("."); if (index != -1) { if (index == 0) { // if the point is the first char, add a 0 for the integer part point = "0".concat(point.substring(1)); } else if (index < point.length() - 1) { // use scale integer for gradePoint point = point.substring(0, index) + point.substring(index + 1); } else { // decimal point is the last char point = point.substring(0, index) + "0"; } } else { // if there is no decimal place, scale up the integer by 10 point = point + "0"; } // filter out the "zero grade" if (point.equals("00")) { point = "0"; } } } return point; } // scalePointGrade /** * Processes formatted text that is coming back from the browser (from the formatted text editing widget). * * @param state * Used to pass in any user-visible alerts or errors when processing the text * @param strFromBrowser * The string from the browser * @param checkForFormattingErrors * Whether to check for formatted text errors - if true, look for errors in the formatted text. If false, accept the formatted text without looking for errors. * @return The formatted text */ private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser, boolean checkForFormattingErrors) { StringBuilder alertMsg = new StringBuilder(); try { boolean replaceWhitespaceTags = true; String text = FormattedText.processFormattedText(strFromBrowser, alertMsg, checkForFormattingErrors, replaceWhitespaceTags); if (alertMsg.length() > 0) addAlert(state, alertMsg.toString()); return text; } catch (Exception e) { Log.warn("chef", this + ": ", e); return strFromBrowser; } } /** * Processes the given assignmnent feedback text, as returned from the user's browser. Makes sure that the Chef-style markup {{like this}} is properly balanced. */ private String processAssignmentFeedbackFromBrowser(SessionState state, String strFromBrowser) { if (strFromBrowser == null || strFromBrowser.length() == 0) return strFromBrowser; StringBuilder buf = new StringBuilder(strFromBrowser); int pos = -1; int numopentags = 0; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<ins>"); numopentags++; } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</ins>"); numopentags--; } while (numopentags > 0) { buf.append("</ins>"); numopentags--; } boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors buf = new StringBuilder(processFormattedTextFromBrowser(state, buf.toString(), checkForFormattingErrors)); while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } /** * Called to deal with old Chef-style assignment feedback annotation, {{like this}}. * * @param value * A formatted text string that may contain {{}} style markup * @return HTML ready to for display on a browser */ public static String escapeAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); StringBuilder buf = new StringBuilder(value); int pos = -1; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<span class='highlight'>"); } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</span>"); } return FormattedText.escapeHtmlFormattedText(buf.toString()); } /** * Escapes the given assignment feedback text, to be edited as formatted text (perhaps using the formatted text widget) */ public static String escapeAssignmentFeedbackTextarea(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); return FormattedText.escapeHtmlFormattedTextarea(value); } /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ private static String fixAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuilder buf = new StringBuilder(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("<br/>")) != -1) { buf.replace(pos, pos + "<br/>".length(), "\n"); } // <span class='chefAlert'>( -> {{ while ((pos = buf.indexOf("<span class='chefAlert'>(")) != -1) { buf.replace(pos, pos + "<span class='chefAlert'>(".length(), "{{"); } // )</span> -> }} while ((pos = buf.indexOf(")</span>")) != -1) { buf.replace(pos, pos + ")</span>".length(), "}}"); } while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } // fixAssignmentFeedback /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ public static String showPrevFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuilder buf = new StringBuilder(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("\n")) != -1) { buf.replace(pos, pos + "\n".length(), "<br />"); } return buf.toString(); } // showPrevFeedback private boolean alertGlobalNavigation(SessionState state, RunData data) { String mode = (String) state.getAttribute(STATE_MODE); ParameterParser params = data.getParameters(); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION) || mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION) || mode.equals(MODE_STUDENT_VIEW_GRADE) || mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_REORDER_ASSIGNMENT)) { if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) == null) { addAlert(state, rb.getString("alert.globalNavi")); state.setAttribute(ALERT_GLOBAL_NAVIGATION, Boolean.TRUE); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatt")); // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { setNewAssignmentParameters(data, false); } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { readGradeForm(data, state, "read"); } return true; } } return false; } // alertGlobalNavigation /** * Dispatch function inside add submission page */ public void doRead_add_submission_form(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("cancel")) { // cancel doCancel_show_submission(data); } else if (option.equals("preview")) { // preview doPreview_submission(data); } else if (option.equals("save")) { // save draft doSave_submission(data); } else if (option.equals("post")) { // post doPost_submission(data); } else if (option.equals("revise")) { // done preview doDone_preview_submission(data); } else if (option.equals("attach")) { // attach ToolSession toolSession = SessionManager.getCurrentToolSession(); String userId = SessionManager.getCurrentSessionUserId(); String siteId = SiteService.getUserSiteId(userId); String collectionId = m_contentHostingService.getSiteCollection(siteId); toolSession.setAttribute(FilePickerHelper.DEFAULT_COLLECTION_ID, collectionId); doAttachments(data); } } /** * Set default score for all ungraded non electronic submissions * @param data */ public void doSet_defaultNotGradedNonElectronicScore(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); String grade = StringUtil.trimToNull(params.getString("defaultGrade")); if (grade == null) { addAlert(state, rb.getString("plespethe2")); } String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); try { // record the default grade setting for no-submission AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade); AssignmentService.commitEdit(aEdit); Assignment a = AssignmentService.getAssignment(assignmentId); if (a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { //for point-based grades validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } } if (grade != null && state.getAttribute(STATE_MESSAGE) == null) { // get the user list List submissions = AssignmentService.getSubmissions(a); for (int i = 0; i<submissions.size(); i++) { // get the submission object AssignmentSubmission submission = (AssignmentSubmission) submissions.get(i); if (submission.getSubmitted() && !submission.getGraded()) { // update the grades for those existing non-submissions AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setGrade(grade); sEdit.setGraded(true); AssignmentService.commitEdit(sEdit); } } } } catch (Exception e) { Log.warn("chef", e.toString()); } } /** * */ public void doSet_defaultNoSubmissionScore(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); String grade = StringUtil.trimToNull(params.getString("defaultGrade")); if (grade == null) { addAlert(state, rb.getString("plespethe2")); } String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); try { // record the default grade setting for no-submission AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade); AssignmentService.commitEdit(aEdit); Assignment a = AssignmentService.getAssignment(assignmentId); if (a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { //for point-based grades validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } } if (grade != null && state.getAttribute(STATE_MESSAGE) == null) { // get the user list List userSubmissions = new Vector(); if (state.getAttribute(USER_SUBMISSIONS) != null) { userSubmissions = (List) state.getAttribute(USER_SUBMISSIONS); } // constructor a new UserSubmissions list List userSubmissionsNew = new Vector(); for (int i = 0; i<userSubmissions.size(); i++) { // get the UserSubmission object UserSubmission us = (UserSubmission) userSubmissions.get(i); User u = us.getUser(); AssignmentSubmission submission = us.getSubmission(); // check whether there is a submission associated if (submission == null) { AssignmentSubmissionEdit s = AssignmentService.addSubmission((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentId, u.getId()); // submitted by without submit time s.setSubmitted(true); s.setGrade(grade); s.setGraded(true); s.setAssignment(a); AssignmentService.commitEdit(s); // update the UserSubmission list by adding newly created Submission object AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference()); userSubmissionsNew.add(new UserSubmission(u, sub)); } else if (StringUtil.trimToNull(submission.getGrade()) == null) { // update the grades for those existing non-submissions AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setGrade(grade); sEdit.setSubmitted(true); sEdit.setGraded(true); AssignmentService.commitEdit(sEdit); userSubmissionsNew.add(new UserSubmission(u, AssignmentService.getSubmission(sEdit.getReference()))); } else if (StringUtil.trimToNull(submission.getGrade()) != null && !submission.getGraded()) { // correct the grade status if there is a grade but the graded is false AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setGraded(true); AssignmentService.commitEdit(sEdit); userSubmissionsNew.add(new UserSubmission(u, AssignmentService.getSubmission(sEdit.getReference()))); } else { // no change for this user userSubmissionsNew.add(us); } } state.setAttribute(USER_SUBMISSIONS, userSubmissionsNew); } } catch (Exception e) { Log.warn("chef", e.toString()); } } /** * * @return */ public void doUpload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String flow = params.getString("flow"); if (flow.equals("upload")) { // upload doUpload_all_upload(data); } else if (flow.equals("cancel")) { // cancel doCancel_upload_all(data); } } public void doUpload_all_upload(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String contextString = ToolManager.getCurrentPlacement().getContext(); String toolTitle = ToolManager.getTool(ASSIGNMENT_TOOL_ID).getTitle(); String aReference = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); String associateGradebookAssignment = null; boolean hasSubmissionText = false; boolean hasSubmissionAttachment = false; boolean hasGradeFile = false; boolean hasFeedbackText = false; boolean hasComment = false; boolean hasFeedbackAttachment = false; boolean releaseGrades = false; // check against the content elements selection if (params.getString("studentSubmissionText") != null) { // should contain student submission text information hasSubmissionText = true; } if (params.getString("studentSubmissionAttachment") != null) { // should contain student submission attachment information hasSubmissionAttachment = true; } if (params.getString("gradeFile") != null) { // should contain grade file hasGradeFile = true; } if (params.getString("feedbackTexts") != null) { // inline text hasFeedbackText = true; } if (params.getString("feedbackComments") != null) { // comments.txt should be available hasComment = true; } if (params.getString("feedbackAttachments") != null) { // feedback attachment hasFeedbackAttachment = true; } if (params.getString("release") != null) { // comments.xml should be available releaseGrades = params.getBoolean("release"); } state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT, Boolean.valueOf(hasSubmissionText)); state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT, Boolean.valueOf(hasSubmissionAttachment)); state.setAttribute(UPLOAD_ALL_HAS_GRADEFILE, Boolean.valueOf(hasGradeFile)); state.setAttribute(UPLOAD_ALL_HAS_COMMENTS, Boolean.valueOf(hasComment)); state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT, Boolean.valueOf(hasFeedbackText)); state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT, Boolean.valueOf(hasFeedbackAttachment)); state.setAttribute(UPLOAD_ALL_RELEASE_GRADES, Boolean.valueOf(releaseGrades)); if (!hasSubmissionText && !hasSubmissionAttachment && !hasFeedbackText && !hasGradeFile && !hasComment && !hasFeedbackAttachment) { // has to choose one upload feature addAlert(state, rb.getString("uploadall.alert.choose.element")); } else { // constructor the hashtable for all submission objects Hashtable submissionTable = new Hashtable(); Assignment assignment = null; List submissions = null; try { assignment = AssignmentService.getAssignment(aReference); associateGradebookAssignment = StringUtil.trimToNull(assignment.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); submissions = AssignmentService.getSubmissions(assignment); if (submissions != null) { Iterator sIterator = submissions.iterator(); while (sIterator.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); User[] users = s.getSubmitters(); if (users.length > 0 && users[0] != null) { submissionTable.put(users[0].getDisplayId(), new UploadGradeWrapper(s.getGrade(), s.getSubmittedText(), s.getFeedbackComment(), s.getSubmittedAttachments(), s.getFeedbackAttachments(), (s.getSubmitted() && s.getTimeSubmitted() != null)?s.getTimeSubmitted().toString():"", s.getFeedbackText())); } } } } catch (Exception e) { Log.warn("chef", e.toString()); } // see if the user uploaded a file FileItem fileFromUpload = null; String fileName = null; fileFromUpload = params.getFileItem("file"); String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1"); int max_bytes = 1024 * 1024; try { max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024; } catch(Exception e) { // if unable to parse an integer from the value // in the properties file, use 1 MB as a default max_file_size_mb = "1"; max_bytes = 1024 * 1024; } if(fileFromUpload == null) { // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded")); } else if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0) { // no file addAlert(state, rb.getString("uploadall.alert.zipFile")); } else { byte[] fileData = fileFromUpload.get(); if(fileData.length >= max_bytes) { addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded")); } else if(fileData.length > 0) { ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(fileData)); ZipEntry entry; try { while ((entry=zin.getNextEntry()) != null) { String entryName = entry.getName(); if (!entry.isDirectory() && entryName.indexOf("/.") == -1) { if (entryName.endsWith("grades.csv")) { if (hasGradeFile) { // read grades.cvs from zip String result = StringUtil.trimToZero(readIntoString(zin)); String[] lines=null; if (result.indexOf("\r\n") != -1) lines = result.split("\r\n"); else if (result.indexOf("\r") != -1) lines = result.split("\r"); else if (result.indexOf("\n") != -1) lines = result.split("\n"); for (int i = 3; i<lines.length; i++) { // escape the first three header lines String[] items = lines[i].split(","); if (items.length > 4) { // has grade information try { User u = UserDirectoryService.getUserByEid(items[1]/*user eid*/); if (u != null) { UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(u.getDisplayId()); if (w != null) { String itemString = items[4]; int gradeType = assignment.getContent().getTypeOfGrade(); if (gradeType == Assignment.SCORE_GRADE_TYPE) { validPointGrade(state, itemString); } else { validLetterGrade(state, itemString); } if (state.getAttribute(STATE_MESSAGE) == null) { w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE?scalePointGrade(state, itemString):itemString); submissionTable.put(u.getDisplayId(), w); } } } } catch (Exception e ) { Log.warn("chef", e.toString()); } } } } } else { // get user eid part String userEid = ""; if (entryName.indexOf("/") != -1) { // remove the part of zip name userEid = entryName.substring(entryName.indexOf("/")+1); // get out the user name part if (userEid.indexOf("/") != -1) { userEid = userEid.substring(0, userEid.indexOf("/")); } // get the eid part if (userEid.indexOf("(") != -1) { userEid = userEid.substring(userEid.indexOf("(")+1, userEid.indexOf(")")); } userEid=StringUtil.trimToNull(userEid); } if (submissionTable.containsKey(userEid)) { if (hasComment && entryName.indexOf("comments") != -1) { // read the comments file String comment = getBodyTextFromZipHtml(zin); if (comment != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setComment(comment); submissionTable.put(userEid, r); } } if (hasFeedbackText && entryName.indexOf("feedbackText") != -1) { // upload the feedback text String text = getBodyTextFromZipHtml(zin); if (text != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setFeedbackText(text); submissionTable.put(userEid, r); } } if (hasSubmissionText && entryName.indexOf("_submissionText") != -1) { // upload the student submission text String text = getBodyTextFromZipHtml(zin); if (text != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setText(text); submissionTable.put(userEid, r); } } if (hasSubmissionAttachment) { // upload the submission attachment String submissionFolder = "/" + rb.getString("download.submission.attachment") + "/"; if ( entryName.indexOf(submissionFolder) != -1) { // clear the submission attachment first UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setSubmissionAttachments(new Vector()); submissionTable.put(userEid, r); uploadZipAttachments(state, submissionTable, zin, entry, entryName, userEid, "submission"); } } if (hasFeedbackAttachment) { // upload the feedback attachment String submissionFolder = "/" + rb.getString("download.feedback.attachment") + "/"; if ( entryName.indexOf(submissionFolder) != -1) { // clear the submission attachment first UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setFeedbackAttachments(new Vector()); submissionTable.put(userEid, r); uploadZipAttachments(state, submissionTable, zin, entry, entryName, userEid, "feedback"); } } // if this is a timestamp file if (entryName.indexOf("timestamp") != -1) { byte[] timeStamp = readIntoBytes(zin, entryName, entry.getSize()); UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setSubmissionTimestamp(new String(timeStamp)); submissionTable.put(userEid, r); } } } } } } catch (IOException e) { // uploaded file is not a valid archive addAlert(state, rb.getString("uploadall.alert.zipFile")); } } } if (state.getAttribute(STATE_MESSAGE) == null) { // update related submissions if (assignment != null && submissions != null) { Iterator sIterator = submissions.iterator(); while (sIterator.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); User[] users = s.getSubmitters(); if (users.length > 0 && users[0] != null) { String uName = users[0].getDisplayId(); if (submissionTable.containsKey(uName)) { // update the AssignmetnSubmission record try { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference()); UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(uName); // the submission text if (hasSubmissionText) { sEdit.setSubmittedText(w.getText()); } // the feedback text if (hasFeedbackText) { sEdit.setFeedbackText(w.getFeedbackText()); } // the submission attachment if (hasSubmissionAttachment) { sEdit.clearSubmittedAttachments(); for (Iterator attachments = w.getSubmissionAttachments().iterator(); attachments.hasNext();) { sEdit.addSubmittedAttachment((Reference) attachments.next()); } } // the feedback attachment if (hasFeedbackAttachment) { sEdit.clearFeedbackAttachments(); for (Iterator attachments = w.getFeedbackAttachments().iterator(); attachments.hasNext();) { sEdit.addFeedbackAttachment((Reference) attachments.next()); } } // the feedback comment if (hasComment) { sEdit.setFeedbackComment(w.getComment()); } // the grade file if (hasGradeFile) { // set grade String grade = StringUtil.trimToNull(w.getGrade()); sEdit.setGrade(grade); if (grade != null && !grade.equals(rb.getString("gen.nograd")) && !grade.equals("ungraded")) sEdit.setGraded(true); } // release or not if (sEdit.getGraded()) { sEdit.setGradeReleased(releaseGrades); sEdit.setReturned(releaseGrades); } else { sEdit.setGradeReleased(false); sEdit.setReturned(false); } if (releaseGrades && sEdit.getGraded()) { sEdit.setTimeReturned(TimeService.newTime()); } // if the current submission lacks timestamp while the timestamp exists inside the zip file if (StringUtil.trimToNull(w.getSubmissionTimeStamp()) != null && sEdit.getTimeSubmitted() == null) { sEdit.setTimeSubmitted(TimeService.newTimeGmt(w.getSubmissionTimeStamp())); sEdit.setSubmitted(true); } // for further information boolean graded = sEdit.getGraded(); String sReference = sEdit.getReference(); // commit AssignmentService.commitEdit(sEdit); if (releaseGrades && graded) { // update grade in gradebook if (associateGradebookAssignment != null) { integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update"); } } } catch (Exception ee) { Log.debug("chef", ee.toString()); } } } } } } } if (state.getAttribute(STATE_MESSAGE) == null) { // go back to the list of submissions view cleanUploadAllContext(state); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } } /** * This is to get the submission or feedback attachment from the upload zip file into the submission object * @param state * @param submissionTable * @param zin * @param entry * @param entryName * @param userEid * @param submissionOrFeedback */ private void uploadZipAttachments(SessionState state, Hashtable submissionTable, ZipInputStream zin, ZipEntry entry, String entryName, String userEid, String submissionOrFeedback) { // upload all the files as instructor attachments to the submission for grading purpose String fName = entryName.substring(entryName.lastIndexOf("/") + 1, entryName.length()); ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); try { // get file extension for detecting content type // ignore those hidden files String extension = ""; if(!fName.contains(".") || (fName.contains(".") && fName.indexOf(".") != 0)) { // add the file as attachment ResourceProperties properties = m_contentHostingService.newResourceProperties(); properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fName); String[] parts = fName.split("\\."); if(parts.length > 1) { extension = parts[parts.length - 1]; } String contentType = ((ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)).getContentType(extension); ContentResourceEdit attachment = m_contentHostingService.addAttachmentResource(fName); attachment.setContent(readIntoBytes(zin, entryName, entry.getSize())); attachment.setContentType(contentType); attachment.getPropertiesEdit().addAll(properties); m_contentHostingService.commitResource(attachment); UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); List attachments = submissionOrFeedback.equals("submission")?r.getSubmissionAttachments():r.getFeedbackAttachments(); attachments.add(EntityManager.newReference(attachment.getReference())); if (submissionOrFeedback.equals("submission")) { r.setSubmissionAttachments(attachments); } else { r.setFeedbackAttachments(attachments); } submissionTable.put(userEid, r); } } catch (Exception ee) { Log.warn("chef", ee.toString()); } } private String getBodyTextFromZipHtml(ZipInputStream zin) { String rv = ""; try { rv = StringUtil.trimToNull(readIntoString(zin)); } catch (IOException e) { Log.debug("chef", this + " " + e.toString()); } if (rv != null) { int start = rv.indexOf("<body>"); int end = rv.indexOf("</body>"); if (start != -1 && end != -1) { // get the text in between rv = rv.substring(start+6, end); } } return rv; } private byte[] readIntoBytes(ZipInputStream zin, String fName, long length) throws IOException { StringBuilder b = new StringBuilder(); byte[] buffer = new byte[4096]; File f = File.createTempFile("asgnup", "tmp"); FileOutputStream fout = new FileOutputStream(f); int len; while ((len = zin.read(buffer)) > 0) { fout.write(buffer, 0, len); } zin.closeEntry(); fout.close(); FileInputStream fis = new FileInputStream(f); FileChannel fc = fis.getChannel(); byte[] data = new byte[(int)(fc.size())]; // fc.size returns the size of the file which backs the channel ByteBuffer bb = ByteBuffer.wrap(data); fc.read(bb); //remove the file fc.close(); // The file channel needs to be closed before the deletion. f.delete(); return data; } private String readIntoString(ZipInputStream zin) throws IOException { StringBuilder buffer = new StringBuilder(); int size = 2048; byte[] data = new byte[2048]; while (true) { try { size = zin.read(data, 0, data.length); if (size > 0) { buffer.append(new String(data, 0, size)); } else { break; } } catch (IOException e) { Log.debug("chef", "readIntoString " + e.toString()); } } return buffer.toString(); } /** * * @return */ public void doCancel_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); cleanUploadAllContext(state); } /** * clean the state variabled used by upload all process */ private void cleanUploadAllContext(SessionState state) { state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_GRADEFILE); state.removeAttribute(UPLOAD_ALL_HAS_COMMENTS); state.removeAttribute(UPLOAD_ALL_RELEASE_GRADES); } /** * Action is to preparing to go to the upload files */ public void doPrep_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_UPLOAD_ALL); } // doPrep_upload_all /** * the UploadGradeWrapper class to be used for the "upload all" feature */ public class UploadGradeWrapper { /** * the grade */ String m_grade = null; /** * the text */ String m_text = null; /** * the submission attachment list */ List m_submissionAttachments = EntityManager.newReferenceList(); /** * the comment */ String m_comment = ""; /** * the timestamp */ String m_timeStamp=""; /** * the feedback text */ String m_feedbackText=""; /** * the feedback attachment list */ List m_feedbackAttachments = EntityManager.newReferenceList(); public UploadGradeWrapper(String grade, String text, String comment, List submissionAttachments, List feedbackAttachments, String timeStamp, String feedbackText) { m_grade = grade; m_text = text; m_comment = comment; m_submissionAttachments = submissionAttachments; m_feedbackAttachments = feedbackAttachments; m_feedbackText = feedbackText; m_timeStamp = timeStamp; } /** * Returns grade string */ public String getGrade() { return m_grade; } /** * Returns the text */ public String getText() { return m_text; } /** * Returns the comment string */ public String getComment() { return m_comment; } /** * Returns the submission attachment list */ public List getSubmissionAttachments() { return m_submissionAttachments; } /** * Returns the feedback attachment list */ public List getFeedbackAttachments() { return m_feedbackAttachments; } /** * submission timestamp * @return */ public String getSubmissionTimeStamp() { return m_timeStamp; } /** * feedback text/incline comment * @return */ public String getFeedbackText() { return m_feedbackText; } /** * set the grade string */ public void setGrade(String grade) { m_grade = grade; } /** * set the text */ public void setText(String text) { m_text = text; } /** * set the comment string */ public void setComment(String comment) { m_comment = comment; } /** * set the submission attachment list */ public void setSubmissionAttachments(List attachments) { m_submissionAttachments = attachments; } /** * set the attachment list */ public void setFeedbackAttachments(List attachments) { m_feedbackAttachments = attachments; } /** * set the submission timestamp */ public void setSubmissionTimestamp(String timeStamp) { m_timeStamp = timeStamp; } /** * set the feedback text */ public void setFeedbackText(String feedbackText) { m_feedbackText = feedbackText; } } private List<DecoratedTaggingProvider> initDecoratedProviders() { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); List<DecoratedTaggingProvider> providers = new ArrayList<DecoratedTaggingProvider>(); for (TaggingProvider provider : taggingManager.getProviders()) { providers.add(new DecoratedTaggingProvider(provider)); } return providers; } private List<DecoratedTaggingProvider> addProviders(Context context, SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); if (providers == null) { providers = initDecoratedProviders(); state.setAttribute(mode + PROVIDER_LIST, providers); } context.put("providers", providers); return providers; } private void addActivity(Context context, Assignment assignment) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("activity", assignmentActivityProducer .getActivity(assignment)); } private void addItem(Context context, AssignmentSubmission submission, String userId) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("item", assignmentActivityProducer .getItem(submission, userId)); } private ContentReviewService contentReviewService; public String getReportURL(Long score) { getContentReviewService(); return contentReviewService.getIconUrlforScore(score); } private void getContentReviewService() { if (contentReviewService == null) { contentReviewService = (ContentReviewService) ComponentManager.get(ContentReviewService.class.getName()); } } }
assignment/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.assignment.tool; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Hashtable; import java.util.HashSet; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.nio.channels.*; import java.nio.*; import org.sakaiproject.announcement.api.AnnouncementChannel; import org.sakaiproject.announcement.api.AnnouncementMessage; import org.sakaiproject.announcement.api.AnnouncementMessageEdit; import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit; import org.sakaiproject.announcement.api.AnnouncementService; import org.sakaiproject.assignment.api.Assignment; import org.sakaiproject.assignment.api.AssignmentContentEdit; import org.sakaiproject.assignment.api.AssignmentEdit; import org.sakaiproject.assignment.api.AssignmentSubmission; import org.sakaiproject.assignment.api.AssignmentSubmissionEdit; import org.sakaiproject.assignment.cover.AssignmentService; import org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer; import org.sakaiproject.assignment.taggable.api.TaggingHelperInfo; import org.sakaiproject.assignment.taggable.api.TaggingManager; import org.sakaiproject.assignment.taggable.api.TaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Pager; import org.sakaiproject.assignment.taggable.tool.DecoratedTaggingProvider.Sort; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.calendar.api.Calendar; import org.sakaiproject.calendar.api.CalendarEvent; import org.sakaiproject.calendar.api.CalendarEventEdit; import org.sakaiproject.calendar.api.CalendarService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.PagedResourceActionII; import org.sakaiproject.cheftool.PortletConfig; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.ContentResourceEdit; import org.sakaiproject.content.api.ContentTypeImageService; import org.sakaiproject.content.api.FilePickerHelper; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentResourceEdit; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.event.cover.NotificationService; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.InUseException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.service.gradebook.shared.AssignmentHasIllegalPointsException; import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException; import org.sakaiproject.service.gradebook.shared.ConflictingExternalIdException; import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.FileItem; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.SortedIterator; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; import org.sakaiproject.contentreview.service.ContentReviewService; /** * <p> * AssignmentAction is the action class for the assignment tool. * </p> */ public class AssignmentAction extends PagedResourceActionII { private static ResourceLoader rb = new ResourceLoader("assignment"); private static final String ASSIGNMENT_TOOL_ID = "sakai.assignment.grades"; private static final Boolean allowReviewService = ServerConfigurationService.getBoolean("assignment.useContentReview", false); /** Is the review service available? */ private static final String ALLOW_REVIEW_SERVICE = "allow_review_service"; private static final String NEW_ASSIGNMENT_USE_REVIEW_SERVICE = "new_assignment_use_review_service"; private static final String NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW = "new_assignment_allow_student_view"; /** The attachments */ private static final String ATTACHMENTS = "Assignment.attachments"; /** The content type image lookup service in the State. */ private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = "Assignment.content_type_image_service"; /** The calendar service in the State. */ private static final String STATE_CALENDAR_SERVICE = "Assignment.calendar_service"; /** The announcement service in the State. */ private static final String STATE_ANNOUNCEMENT_SERVICE = "Assignment.announcement_service"; /** The calendar object */ private static final String CALENDAR = "calendar"; /** The calendar tool */ private static final String CALENDAR_TOOL_EXIST = "calendar_tool_exisit"; /** The announcement tool */ private static final String ANNOUNCEMENT_TOOL_EXIST = "announcement_tool_exist"; /** The announcement channel */ private static final String ANNOUNCEMENT_CHANNEL = "announcement_channel"; /** The state mode */ private static final String STATE_MODE = "Assignment.mode"; /** The context string */ private static final String STATE_CONTEXT_STRING = "Assignment.context_string"; /** The user */ private static final String STATE_USER = "Assignment.user"; // SECTION MOD /** Used to keep track of the section info not currently being used. */ private static final String STATE_SECTION_STRING = "Assignment.section_string"; /** **************************** sort assignment ********************** */ /** state sort * */ private static final String SORTED_BY = "Assignment.sorted_by"; /** state sort ascendingly * */ private static final String SORTED_ASC = "Assignment.sorted_asc"; /** default sorting */ private static final String SORTED_BY_DEFAULT = "default"; /** sort by assignment title */ private static final String SORTED_BY_TITLE = "title"; /** sort by assignment section */ private static final String SORTED_BY_SECTION = "section"; /** sort by assignment due date */ private static final String SORTED_BY_DUEDATE = "duedate"; /** sort by assignment open date */ private static final String SORTED_BY_OPENDATE = "opendate"; /** sort by assignment status */ private static final String SORTED_BY_ASSIGNMENT_STATUS = "assignment_status"; /** sort by assignment submission status */ private static final String SORTED_BY_SUBMISSION_STATUS = "submission_status"; /** sort by assignment number of submissions */ private static final String SORTED_BY_NUM_SUBMISSIONS = "num_submissions"; /** sort by assignment number of ungraded submissions */ private static final String SORTED_BY_NUM_UNGRADED = "num_ungraded"; /** sort by assignment submission grade */ private static final String SORTED_BY_GRADE = "grade"; /** sort by assignment maximun grade available */ private static final String SORTED_BY_MAX_GRADE = "max_grade"; /** sort by assignment range */ private static final String SORTED_BY_FOR = "for"; /** sort by group title */ private static final String SORTED_BY_GROUP_TITLE = "group_title"; /** sort by group description */ private static final String SORTED_BY_GROUP_DESCRIPTION = "group_description"; /** *************************** sort submission in instructor grade view *********************** */ /** state sort submission* */ private static final String SORTED_GRADE_SUBMISSION_BY = "Assignment.grade_submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_GRADE_SUBMISSION_ASC = "Assignment.grade_submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_GRADE_SUBMISSION_BY_LASTNAME = "sorted_grade_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME = "sorted_grade_submission_by_submit_time"; /** state sort submission by submission status * */ private static final String SORTED_GRADE_SUBMISSION_BY_STATUS = "sorted_grade_submission_by_status"; /** state sort submission by submission grade * */ private static final String SORTED_GRADE_SUBMISSION_BY_GRADE = "sorted_grade_submission_by_grade"; /** state sort submission by submission released * */ private static final String SORTED_GRADE_SUBMISSION_BY_RELEASED = "sorted_grade_submission_by_released"; /** state sort submissuib by content review score **/ private static final String SORTED_GRADE_SUBMISSION_CONTENTREVIEW = "sorted_grade_submission_by_contentreview"; /** *************************** sort submission *********************** */ /** state sort submission* */ private static final String SORTED_SUBMISSION_BY = "Assignment.submission_sorted_by"; /** state sort submission ascendingly * */ private static final String SORTED_SUBMISSION_ASC = "Assignment.submission_sorted_asc"; /** state sort submission by submitters last name * */ private static final String SORTED_SUBMISSION_BY_LASTNAME = "sorted_submission_by_lastname"; /** state sort submission by submit time * */ private static final String SORTED_SUBMISSION_BY_SUBMIT_TIME = "sorted_submission_by_submit_time"; /** state sort submission by submission grade * */ private static final String SORTED_SUBMISSION_BY_GRADE = "sorted_submission_by_grade"; /** state sort submission by submission status * */ private static final String SORTED_SUBMISSION_BY_STATUS = "sorted_submission_by_status"; /** state sort submission by submission released * */ private static final String SORTED_SUBMISSION_BY_RELEASED = "sorted_submission_by_released"; /** state sort submission by assignment title */ private static final String SORTED_SUBMISSION_BY_ASSIGNMENT = "sorted_submission_by_assignment"; /** state sort submission by max grade */ private static final String SORTED_SUBMISSION_BY_MAX_GRADE = "sorted_submission_by_max_grade"; /*********************** Sort by user sort name *****************************************/ private static final String SORTED_USER_BY_SORTNAME = "sorted_user_by_sortname"; /** ******************** student's view assignment submission ****************************** */ /** the assignment object been viewing * */ private static final String VIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "Assignment.view_submission_assignment_reference"; /** the submission text to the assignment * */ private static final String VIEW_SUBMISSION_TEXT = "Assignment.view_submission_text"; /** the submission answer to Honor Pledge * */ private static final String VIEW_SUBMISSION_HONOR_PLEDGE_YES = "Assignment.view_submission_honor_pledge_yes"; /** ***************** student's preview of submission *************************** */ /** the assignment id * */ private static final String PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE = "preview_submission_assignment_reference"; /** the submission text * */ private static final String PREVIEW_SUBMISSION_TEXT = "preview_submission_text"; /** the submission honor pledge answer * */ private static final String PREVIEW_SUBMISSION_HONOR_PLEDGE_YES = "preview_submission_honor_pledge_yes"; /** the submission attachments * */ private static final String PREVIEW_SUBMISSION_ATTACHMENTS = "preview_attachments"; /** the flag indicate whether the to show the student view or not */ private static final String PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG = "preview_assignment_student_view_hide_flag"; /** the flag indicate whether the to show the assignment info or not */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG = "preview_assignment_assignment_hide_flag"; /** the assignment id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENT_ID = "preview_assignment_assignment_id"; /** the assignment content id */ private static final String PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID = "preview_assignment_assignmentcontent_id"; /** ************** view assignment ***************************************** */ /** the hide assignment flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG = "view_assignment_hide_assignment_flag"; /** the hide student view flag in the view assignment page * */ private static final String VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG = "view_assignment_hide_student_view_flag"; /** ******************* instructor's view assignment ***************************** */ private static final String VIEW_ASSIGNMENT_ID = "view_assignment_id"; /** ******************* instructor's edit assignment ***************************** */ private static final String EDIT_ASSIGNMENT_ID = "edit_assignment_id"; /** ******************* instructor's delete assignment ids ***************************** */ private static final String DELETE_ASSIGNMENT_IDS = "delete_assignment_ids"; /** ******************* flags controls the grade assignment page layout ******************* */ private static final String GRADE_ASSIGNMENT_EXPAND_FLAG = "grade_assignment_expand_flag"; private static final String GRADE_SUBMISSION_EXPAND_FLAG = "grade_submission_expand_flag"; private static final String GRADE_NO_SUBMISSION_DEFAULT_GRADE = "grade_no_submission_default_grade"; /** ******************* instructor's grade submission ***************************** */ private static final String GRADE_SUBMISSION_ASSIGNMENT_ID = "grade_submission_assignment_id"; private static final String GRADE_SUBMISSION_SUBMISSION_ID = "grade_submission_submission_id"; private static final String GRADE_SUBMISSION_FEEDBACK_COMMENT = "grade_submission_feedback_comment"; private static final String GRADE_SUBMISSION_FEEDBACK_TEXT = "grade_submission_feedback_text"; private static final String GRADE_SUBMISSION_FEEDBACK_ATTACHMENT = "grade_submission_feedback_attachment"; private static final String GRADE_SUBMISSION_GRADE = "grade_submission_grade"; private static final String GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG = "grade_submission_assignment_expand_flag"; private static final String GRADE_SUBMISSION_ALLOW_RESUBMIT = "grade_submission_allow_resubmit"; /** ******************* instructor's export assignment ***************************** */ private static final String EXPORT_ASSIGNMENT_REF = "export_assignment_ref"; /** * Is review service enabled? */ private static final String ENABLE_REVIEW_SERVICE = "enable_review_service"; private static final String EXPORT_ASSIGNMENT_ID = "export_assignment_id"; /** ****************** instructor's new assignment ****************************** */ private static final String NEW_ASSIGNMENT_TITLE = "new_assignment_title"; // assignment order for default view private static final String NEW_ASSIGNMENT_ORDER = "new_assignment_order"; // open date private static final String NEW_ASSIGNMENT_OPENMONTH = "new_assignment_openmonth"; private static final String NEW_ASSIGNMENT_OPENDAY = "new_assignment_openday"; private static final String NEW_ASSIGNMENT_OPENYEAR = "new_assignment_openyear"; private static final String NEW_ASSIGNMENT_OPENHOUR = "new_assignment_openhour"; private static final String NEW_ASSIGNMENT_OPENMIN = "new_assignment_openmin"; private static final String NEW_ASSIGNMENT_OPENAMPM = "new_assignment_openampm"; // due date private static final String NEW_ASSIGNMENT_DUEMONTH = "new_assignment_duemonth"; private static final String NEW_ASSIGNMENT_DUEDAY = "new_assignment_dueday"; private static final String NEW_ASSIGNMENT_DUEYEAR = "new_assignment_dueyear"; private static final String NEW_ASSIGNMENT_DUEHOUR = "new_assignment_duehour"; private static final String NEW_ASSIGNMENT_DUEMIN = "new_assignment_duemin"; private static final String NEW_ASSIGNMENT_DUEAMPM = "new_assignment_dueampm"; private static final String NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID = "new_assignment_duedate_calendar_assignment_id"; private static final String NEW_ASSIGNMENT_PAST_DUE_DATE = "new_assignment_past_due_date"; // close date private static final String NEW_ASSIGNMENT_ENABLECLOSEDATE = "new_assignment_enableclosedate"; private static final String NEW_ASSIGNMENT_CLOSEMONTH = "new_assignment_closemonth"; private static final String NEW_ASSIGNMENT_CLOSEDAY = "new_assignment_closeday"; private static final String NEW_ASSIGNMENT_CLOSEYEAR = "new_assignment_closeyear"; private static final String NEW_ASSIGNMENT_CLOSEHOUR = "new_assignment_closehour"; private static final String NEW_ASSIGNMENT_CLOSEMIN = "new_assignment_closemin"; private static final String NEW_ASSIGNMENT_CLOSEAMPM = "new_assignment_closeampm"; private static final String NEW_ASSIGNMENT_ATTACHMENT = "new_assignment_attachment"; private static final String NEW_ASSIGNMENT_SECTION = "new_assignment_section"; private static final String NEW_ASSIGNMENT_SUBMISSION_TYPE = "new_assignment_submission_type"; private static final String NEW_ASSIGNMENT_GRADE_TYPE = "new_assignment_grade_type"; private static final String NEW_ASSIGNMENT_GRADE_POINTS = "new_assignment_grade_points"; private static final String NEW_ASSIGNMENT_DESCRIPTION = "new_assignment_instructions"; private static final String NEW_ASSIGNMENT_DUE_DATE_SCHEDULED = "new_assignment_due_date_scheduled"; private static final String NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED = "new_assignment_open_date_announced"; private static final String NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE = "new_assignment_check_add_honor_pledge"; private static final String NEW_ASSIGNMENT_HIDE_OPTION_FLAG = "new_assignment_hide_option_flag"; private static final String NEW_ASSIGNMENT_FOCUS = "new_assignment_focus"; private static final String NEW_ASSIGNMENT_DESCRIPTION_EMPTY = "new_assignment_description_empty"; private static final String NEW_ASSIGNMENT_ADD_TO_GRADEBOOK = "new_assignment_add_to_gradebook"; private static final String NEW_ASSIGNMENT_RANGE = "new_assignment_range"; private static final String NEW_ASSIGNMENT_GROUPS = "new_assignment_groups"; private static final String NEW_ASSIGNMENT_PAST_CLOSE_DATE = "new_assignment_past_close_date"; /**************************** assignment year range *************************/ private static final String NEW_ASSIGNMENT_YEAR_RANGE_FROM = "new_assignment_year_range_from"; private static final String NEW_ASSIGNMENT_YEAR_RANGE_TO = "new_assignment_year_range_to"; // submission level of resubmit due time private static final String ALLOW_RESUBMIT_CLOSEMONTH = "allow_resubmit_closeMonth"; private static final String ALLOW_RESUBMIT_CLOSEDAY = "allow_resubmit_closeDay"; private static final String ALLOW_RESUBMIT_CLOSEYEAR = "allow_resubmit_closeYear"; private static final String ALLOW_RESUBMIT_CLOSEHOUR = "allow_resubmit_closeHour"; private static final String ALLOW_RESUBMIT_CLOSEMIN = "allow_resubmit_closeMin"; private static final String ALLOW_RESUBMIT_CLOSEAMPM = "allow_resubmit_closeAMPM"; private static final String ATTACHMENTS_MODIFIED = "attachments_modified"; /** **************************** instructor's view student submission ***************** */ // the show/hide table based on member id private static final String STUDENT_LIST_SHOW_TABLE = "STUDENT_LIST_SHOW_TABLE"; /** **************************** student view grade submission id *********** */ private static final String VIEW_GRADE_SUBMISSION_ID = "view_grade_submission_id"; // alert for grade exceeds max grade setting private static final String GRADE_GREATER_THAN_MAX_ALERT = "grade_greater_than_max_alert"; /** **************************** modes *************************** */ /** The list view of assignments */ private static final String MODE_LIST_ASSIGNMENTS = "lisofass1"; // set in velocity template /** The student view of an assignment submission */ private static final String MODE_STUDENT_VIEW_SUBMISSION = "Assignment.mode_view_submission"; /** The student view of an assignment submission confirmation */ private static final String MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "Assignment.mode_view_submission_confirmation"; /** The student preview of an assignment submission */ private static final String MODE_STUDENT_PREVIEW_SUBMISSION = "Assignment.mode_student_preview_submission"; /** The student view of graded submission */ private static final String MODE_STUDENT_VIEW_GRADE = "Assignment.mode_student_view_grade"; /** The student view of assignments */ private static final String MODE_STUDENT_VIEW_ASSIGNMENT = "Assignment.mode_student_view_assignment"; /** The instructor view of creating a new assignment or editing an existing one */ private static final String MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "Assignment.mode_instructor_new_edit_assignment"; /** The instructor view to reorder assignments */ private static final String MODE_INSTRUCTOR_REORDER_ASSIGNMENT = "reorder"; /** The instructor view to delete an assignment */ private static final String MODE_INSTRUCTOR_DELETE_ASSIGNMENT = "Assignment.mode_instructor_delete_assignment"; /** The instructor view to grade an assignment */ private static final String MODE_INSTRUCTOR_GRADE_ASSIGNMENT = "Assignment.mode_instructor_grade_assignment"; /** The instructor view to grade a submission */ private static final String MODE_INSTRUCTOR_GRADE_SUBMISSION = "Assignment.mode_instructor_grade_submission"; /** The instructor view of preview grading a submission */ private static final String MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "Assignment.mode_instructor_preview_grade_submission"; /** The instructor preview of one assignment */ private static final String MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "Assignment.mode_instructor_preview_assignments"; /** The instructor view of one assignment */ private static final String MODE_INSTRUCTOR_VIEW_ASSIGNMENT = "Assignment.mode_instructor_view_assignments"; /** The instructor view to list students of an assignment */ private static final String MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "lisofass2"; // set in velocity template /** The instructor view of assignment submission report */ private static final String MODE_INSTRUCTOR_REPORT_SUBMISSIONS = "grarep"; // set in velocity template /** The instructor view of uploading all from archive file */ private static final String MODE_INSTRUCTOR_UPLOAD_ALL = "uploadAll"; /** The student view of assignment submission report */ private static final String MODE_STUDENT_VIEW = "stuvie"; // set in velocity template /** ************************* vm names ************************** */ /** The list view of assignments */ private static final String TEMPLATE_LIST_ASSIGNMENTS = "_list_assignments"; /** The student view of assignment */ private static final String TEMPLATE_STUDENT_VIEW_ASSIGNMENT = "_student_view_assignment"; /** The student view of showing an assignment submission */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION = "_student_view_submission"; /** The student view of an assignment submission confirmation */ private static final String TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION = "_student_view_submission_confirmation"; /** The student preview an assignment submission */ private static final String TEMPLATE_STUDENT_PREVIEW_SUBMISSION = "_student_preview_submission"; /** The student view of graded submission */ private static final String TEMPLATE_STUDENT_VIEW_GRADE = "_student_view_grade"; /** The instructor view to create a new assignment or edit an existing one */ private static final String TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT = "_instructor_new_edit_assignment"; /** The instructor view to reorder the default assignments */ private static final String TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT = "_instructor_reorder_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT = "_instructor_delete_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION = "_instructor_grading_submission"; /** The instructor preview to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION = "_instructor_preview_grading_submission"; /** The instructor view to grade the assignment */ private static final String TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT = "_instructor_list_submissions"; /** The instructor preview of assignment */ private static final String TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT = "_instructor_preview_assignment"; /** The instructor view of assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT = "_instructor_view_assignment"; /** The instructor view to edit assignment */ private static final String TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT = "_instructor_student_list_submissions"; /** The instructor view to assignment submission report */ private static final String TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS = "_instructor_report_submissions"; /** The instructor view to upload all information from archive file */ private static final String TEMPLATE_INSTRUCTOR_UPLOAD_ALL = "_instructor_uploadAll"; /** The opening mark comment */ private static final String COMMENT_OPEN = "{{"; /** The closing mark for comment */ private static final String COMMENT_CLOSE = "}}"; /** The selected view */ private static final String STATE_SELECTED_VIEW = "state_selected_view"; /** The configuration choice of with grading option or not */ private static final String WITH_GRADES = "with_grades"; /** The alert flag when doing global navigation from improper mode */ private static final String ALERT_GLOBAL_NAVIGATION = "alert_global_navigation"; /** The total list item before paging */ private static final String STATE_PAGEING_TOTAL_ITEMS = "state_paging_total_items"; /** is current user allowed to grade assignment? */ private static final String STATE_ALLOW_GRADE_SUBMISSION = "state_allow_grade_submission"; /** property for previous feedback attachments **/ private static final String PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS = "prop_submission_previous_feedback_attachments"; /** the user and submission list for list of submissions page */ private static final String USER_SUBMISSIONS = "user_submissions"; /** ************************* Taggable constants ************************** */ /** identifier of tagging provider that will provide the appropriate helper */ private static final String PROVIDER_ID = "providerId"; /** Reference to an activity */ private static final String ACTIVITY_REF = "activityRef"; /** Reference to an item */ private static final String ITEM_REF = "itemRef"; /** session attribute for list of decorated tagging providers */ private static final String PROVIDER_LIST = "providerList"; // whether the choice of emails instructor submission notification is available in the installation private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS = "assignment.instructor.notifications"; // default for whether or how the instructor receive submission notification emails, none(default)|each|digest private static final String ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT = "assignment.instructor.notifications.default"; /****************************** Upload all screen ***************************/ private static final String UPLOAD_ALL_HAS_SUBMISSION_TEXT = "upload_all_has_submission_text"; private static final String UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT = "upload_all_has_submission_attachment"; private static final String UPLOAD_ALL_HAS_GRADEFILE = "upload_all_has_gradefile"; private static final String UPLOAD_ALL_HAS_COMMENTS= "upload_all_has_comments"; private static final String UPLOAD_ALL_HAS_FEEDBACK_TEXT= "upload_all_has_feedback_text"; private static final String UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT = "upload_all_has_feedback_attachment"; private static final String UPLOAD_ALL_RELEASE_GRADES = "upload_all_release_grades"; // this is to track whether the site has multiple assignment, hence if true, show the reorder link private static final String HAS_MULTIPLE_ASSIGNMENTS = "has_multiple_assignments"; // view all or grouped submission list private static final String VIEW_SUBMISSION_LIST_OPTION = "view_submission_list_option"; private ContentHostingService m_contentHostingService = null; /** * central place for dispatching the build routines based on the state name */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String template = null; context.put("tlang", rb); context.put("cheffeedbackhelper", this); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // allow add assignment? boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); context.put("allowAddAssignment", Boolean.valueOf(allowAddAssignment)); Object allowGradeSubmission = state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION); // allow update site? context.put("allowUpdateSite", Boolean .valueOf(SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING)))); // allow all.groups? boolean allowAllGroups = AssignmentService.allowAllGroups(contextString); context.put("allowAllGroups", Boolean.valueOf(allowAllGroups)); //Is the review service allowed? Site s = null; try { s = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (IdUnusedException iue) { Log.warn("chef", "Site not found!"); } getContentReviewService(); if (allowReviewService && contentReviewService.isSiteAcceptable(s)) { context.put("allowReviewService", allowReviewService); } else { context.put("allowReviewService", false); } // grading option context.put("withGrade", state.getAttribute(WITH_GRADES)); // the grade type table context.put("gradeTypeTable", gradeTypeTable()); String mode = (String) state.getAttribute(STATE_MODE); if (!mode.equals(MODE_LIST_ASSIGNMENTS)) { // allow grade assignment? if (state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION) == null) { state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, Boolean.FALSE); } context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); } if (mode.equals(MODE_LIST_ASSIGNMENTS)) { // build the context for the student assignment view template = build_list_assignments_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_ASSIGNMENT)) { // the student view of assignment template = build_student_view_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one assignment submission template = build_student_view_submission_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION)) { // build the context for showing one assignment submission confirmation template = build_student_view_submission_confirmation_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION)) { // build the context for showing one assignment submission template = build_student_preview_submission_context(portlet, context, data, state); } else if (mode.equals(MODE_STUDENT_VIEW_GRADE)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for showing one graded submission template = build_student_view_grade_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { // allow add assignment? boolean allowAddSiteAssignment = AssignmentService.allowAddSiteAssignment(contextString); context.put("allowAddSiteAssignment", Boolean.valueOf(allowAddSiteAssignment)); // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_new_edit_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT)) { if (state.getAttribute(DELETE_ASSIGNMENT_IDS) != null) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's delete assignment template = build_instructor_delete_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_GRADE_ASSIGNMENT)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's grade assignment template = build_instructor_grade_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { if (allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's grade submission template = build_instructor_grade_submission_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's preview grade submission template = build_instructor_preview_grade_submission_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)) { // build the context for preview one assignment template = build_instructor_preview_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for view one assignment template = build_instructor_view_assignment_context(portlet, context, data, state); } else if (mode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's create new assignment view template = build_instructor_view_students_assignment_context(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of report submissions template = build_instructor_report_submissions(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_UPLOAD_ALL)) { if ( allowGradeSubmission != null && ((Boolean) allowGradeSubmission).booleanValue()) { // if allowed for grading, build the context for the instructor's view of uploading all info from archive file template = build_instructor_upload_all(portlet, context, data, state); } } else if (mode.equals(MODE_INSTRUCTOR_REORDER_ASSIGNMENT)) { // disable auto-updates while leaving the list view justDelivered(state); // build the context for the instructor's create new assignment view template = build_instructor_reorder_assignment_context(portlet, context, data, state); } if (template == null) { // default to student list view state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); template = build_list_assignments_context(portlet, context, data, state); } // this is a check for seeing if there are any assignments. The check is used to see if we display a Reorder link in the vm files if (state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS) != null) { context.put("assignmentscheck", state.getAttribute(HAS_MULTIPLE_ASSIGNMENTS)); } return template; } // buildNormalContext /** * build the student view of showing an assignment submission */ protected String build_student_view_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); User user = (User) state.getAttribute(STATE_USER); String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment assignment = null; try { assignment = AssignmentService.getAssignment(currentAssignmentReference); context.put("assignment", assignment); context.put("canSubmit", Boolean.valueOf(AssignmentService.canSubmit(contextString, assignment))); if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { context.put("nonElectronicType", Boolean.TRUE); } AssignmentSubmission s = AssignmentService.getSubmission(assignment.getReference(), user); if (s != null) { context.put("submission", s); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } // name value pairs for the vm context.put("name_submission_text", VIEW_SUBMISSION_TEXT); context.put("value_submission_text", state.getAttribute(VIEW_SUBMISSION_TEXT)); context.put("name_submission_honor_pledge_yes", VIEW_SUBMISSION_HONOR_PLEDGE_YES); context.put("value_submission_honor_pledge_yes", state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("currentTime", TimeService.newTime()); boolean allowSubmit = AssignmentService.allowAddSubmission((String) state.getAttribute(STATE_CONTEXT_STRING)); if (!allowSubmit) { addAlert(state, rb.getString("not_allowed_to_submit")); } context.put("allowSubmit", new Boolean(allowSubmit)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION; } // build_student_view_submission_context /** * build the student view of showing an assignment submission confirmation */ protected String build_student_view_submission_confirmation_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("context", contextString); // get user information User user = (User) state.getAttribute(STATE_USER); context.put("user_name", user.getDisplayName()); context.put("user_id", user.getDisplayId()); if (StringUtil.trimToNull(user.getEmail()) != null) context.put("user_email", user.getEmail()); // get site information try { // get current site Site site = SiteService.getSite(contextString); context.put("site_title", site.getTitle()); } catch (Exception ignore) { Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString); } // get assignment and submission information String currentAssignmentReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { Assignment currentAssignment = AssignmentService.getAssignment(currentAssignmentReference); context.put("assignment_title", currentAssignment.getTitle()); AssignmentSubmission s = AssignmentService.getSubmission(currentAssignment.getReference(), user); if (s != null) { context.put("submitted", Boolean.valueOf(s.getSubmitted())); context.put("submission_id", s.getId()); if (s.getTimeSubmitted() != null) { context.put("submit_time", s.getTimeSubmitted().toStringLocalFull()); } List attachments = s.getSubmittedAttachments(); if (attachments != null && attachments.size()>0) { context.put("submit_attachments", s.getSubmittedAttachments()); } context.put("submit_text", StringUtil.trimToNull(s.getSubmittedText())); context.put("email_confirmation", Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.submission.confirmation.email", true))); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_SUBMISSION_CONFIRMATION; } // build_student_view_submission_confirmation_context /** * build the student view of assignment */ protected String build_student_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); String aId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); Assignment assignment = null; try { assignment = AssignmentService.getAssignment(aId); context.put("assignment", assignment); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannot_find_assignment")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_ASSIGNMENT; } // build_student_view_submission_context /** * build the student preview of showing an assignment submission */ protected String build_student_preview_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { User user = (User) state.getAttribute(STATE_USER); String aReference = (String) state.getAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE); try { context.put("assignment", AssignmentService.getAssignment(aReference)); context.put("submission", AssignmentService.getSubmission(aReference, user)); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot16")); } context.put("text", state.getAttribute(PREVIEW_SUBMISSION_TEXT)); context.put("honor_pledge_yes", state.getAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES)); context.put("attachments", state.getAttribute(PREVIEW_SUBMISSION_ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_PREVIEW_SUBMISSION; } // build_student_preview_submission_context /** * build the student view of showing a graded submission */ protected String build_student_view_grade_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); AssignmentSubmission submission = null; try { submission = AssignmentService.getSubmission((String) state.getAttribute(VIEW_GRADE_SUBMISSION_ID)); Assignment assignment = submission.getAssignment(); context.put("assignment", assignment); if (assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { context.put("nonElectronicType", Boolean.TRUE); } context.put("submission", submission); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_get_submission")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && submission != null) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> itemHelpers = new ArrayList<TaggingHelperInfo>(); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getItemHelperInfo( assignmentActivityProducer.getItem( submission, UserDirectoryService.getCurrentUser() .getId()).getReference()); if (helper != null) { itemHelpers.add(helper); } } addItem(context, submission, UserDirectoryService.getCurrentUser().getId()); addActivity(context, submission.getAssignment()); context.put("itemHelpers", itemHelpers); context.put("taggable", Boolean.valueOf(true)); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_VIEW_GRADE; } // build_student_view_grade_context /** * build the view of assignments list */ protected String build_list_assignments_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable()) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); context.put("providers", taggingManager.getProviders()); context.put("taggable", Boolean.valueOf(true)); } String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("contextString", contextString); context.put("user", state.getAttribute(STATE_USER)); context.put("service", AssignmentService.getInstance()); context.put("TimeService", TimeService.getInstance()); context.put("LongObject", new Long(TimeService.newTime().getTime())); context.put("currentTime", TimeService.newTime()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); // clean sort criteria if (sortedBy.equals(SORTED_BY_GROUP_TITLE) || sortedBy.equals(SORTED_BY_GROUP_DESCRIPTION)) { sortedBy = SORTED_BY_DUEDATE; sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sortedBy); state.setAttribute(SORTED_ASC, sortedAsc); } context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); if (state.getAttribute(STATE_SELECTED_VIEW) != null) { context.put("view", state.getAttribute(STATE_SELECTED_VIEW)); } Hashtable assignments_submissions = new Hashtable(); List assignments = prepPage(state); context.put("assignments", assignments.iterator()); // allow get assignment context.put("allowGetAssignment", Boolean.valueOf(AssignmentService.allowGetAssignment(contextString))); // test whether user user can grade at least one assignment // and update the state variable. boolean allowGradeSubmission = false; for (Iterator aIterator=assignments.iterator(); !allowGradeSubmission && aIterator.hasNext(); ) { if (AssignmentService.allowGradeSubmission(((Assignment) aIterator.next()).getReference())) { allowGradeSubmission = true; } } state.setAttribute(STATE_ALLOW_GRADE_SUBMISSION, new Boolean(allowGradeSubmission)); context.put("allowGradeSubmission", state.getAttribute(STATE_ALLOW_GRADE_SUBMISSION)); // allow remove assignment? boolean allowRemoveAssignment = false; for (Iterator aIterator=assignments.iterator(); !allowRemoveAssignment && aIterator.hasNext(); ) { if (AssignmentService.allowRemoveAssignment(((Assignment) aIterator.next()).getReference())) { allowRemoveAssignment = true; } } context.put("allowRemoveAssignment", Boolean.valueOf(allowRemoveAssignment)); add2ndToolbarFields(data, context); // inform the observing courier that we just updated the page... // if there are pending requests to do so they can be cleared justDelivered(state); pagingInfoToContext(state, context); // put site object into context try { // get current site Site site = SiteService.getSite(contextString); context.put("site", site); // any group in the site? Collection groups = site.getGroups(); context.put("groups", (groups != null && groups.size()>0)?Boolean.TRUE:Boolean.FALSE); // add active user list AuthzGroup realm = AuthzGroupService.getAuthzGroup(SiteService.siteReference(contextString)); if (realm != null) { context.put("activeUserIds", realm.getUsers()); } } catch (Exception ignore) { Log.warn("chef", this + ignore.getMessage() + " siteId= " + contextString); } boolean allowSubmit = AssignmentService.allowAddSubmission(contextString); context.put("allowSubmit", new Boolean(allowSubmit)); // related to resubmit settings context.put("allowResubmitNumberProp", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); context.put("allowResubmitCloseTimeProp", AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); // the type int for non-electronic submission context.put("typeNonElectronic", Integer.valueOf(Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_LIST_ASSIGNMENTS; } // build_list_assignments_context private HashSet<String> getSubmittersIdSet(List submissions) { HashSet<String> rv = new HashSet<String>(); for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext();) { List submitterIds = ((AssignmentSubmission) iSubmissions.next()).getSubmitterIds(); if (submitterIds != null && submitterIds.size() > 0) { rv.add((String) submitterIds.get(0)); } } return rv; } private HashSet<String> getAllowAddSubmissionUsersIdSet(List users) { HashSet<String> rv = new HashSet<String>(); for (Iterator iUsers=users.iterator(); iUsers.hasNext();) { rv.add(((User) iUsers.next()).getId()); } return rv; } /** * build the instructor view of creating a new assignment or editing an existing one */ protected String build_instructor_new_edit_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // is the assignment an new assignment String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID); if (assignmentId != null) { try { Assignment a = AssignmentService.getAssignment(assignmentId); context.put("assignment", a); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3") + ": " + assignmentId); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14") + ": " + assignmentId); } } // set up context variables setAssignmentFormContext(state, context); context.put("fField", state.getAttribute(NEW_ASSIGNMENT_FOCUS)); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT; } // build_instructor_new_assignment_context protected void setAssignmentFormContext(SessionState state, Context context) { // put the names and values into vm file context.put("name_UseReviewService", NEW_ASSIGNMENT_USE_REVIEW_SERVICE); context.put("name_AllowStudentView", NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW); context.put("name_title", NEW_ASSIGNMENT_TITLE); context.put("name_order", NEW_ASSIGNMENT_ORDER); // set open time context variables putTimePropertiesInContext(context, state, "Open", NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN, NEW_ASSIGNMENT_OPENAMPM); // set due time context variables putTimePropertiesInContext(context, state, "Due", NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN, NEW_ASSIGNMENT_DUEAMPM); context.put("name_EnableCloseDate", NEW_ASSIGNMENT_ENABLECLOSEDATE); // set close time context variables putTimePropertiesInContext(context, state, "Close", NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN, NEW_ASSIGNMENT_CLOSEAMPM); context.put("name_Section", NEW_ASSIGNMENT_SECTION); context.put("name_SubmissionType", NEW_ASSIGNMENT_SUBMISSION_TYPE); context.put("name_GradeType", NEW_ASSIGNMENT_GRADE_TYPE); context.put("name_GradePoints", NEW_ASSIGNMENT_GRADE_POINTS); context.put("name_Description", NEW_ASSIGNMENT_DESCRIPTION); // do not show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null) context.put("name_CheckAddDueDate", ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); //don't show the choice when there is no Announcement tool yet if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null) context.put("name_CheckAutoAnnounce", ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); context.put("name_CheckAddHonorPledge", NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // number of resubmissions allowed context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // set the values context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); context.put("value_title", state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("value_position_order", state.getAttribute(NEW_ASSIGNMENT_ORDER)); context.put("value_EnableCloseDate", state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)); context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_totalSubmissionTypes", Assignment.SUBMISSION_TYPES.length); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); // format to show one decimal place String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); // Keep the use review service setting context.put("value_UseReviewService", state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE)); context.put("value_AllowStudentView", state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW)); // don't show the choice when there is no Schedule tool yet if (state.getAttribute(CALENDAR) != null) context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); // don't show the choice when there is no Announcement tool yet if (state.getAttribute(ANNOUNCEMENT_CHANNEL) != null) context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); String s = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); if (s == null) s = "1"; context.put("value_CheckAddHonorPledge", s); // number of resubmissions allowed if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER))); } else { // defaults to 0 context.put("value_allowResubmitNumber", Integer.valueOf(0)); } // get all available assignments from Gradebook tool except for those created from boolean gradebookExists = isGradebookDefined(); if (gradebookExists) { GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); try { // get all assignments in Gradebook List gradebookAssignments = g.getAssignments(gradebookUid); List gradebookAssignmentsExceptSamigo = new Vector(); // filtering out those from Samigo for (Iterator i=gradebookAssignments.iterator(); i.hasNext();) { org.sakaiproject.service.gradebook.shared.Assignment gAssignment = (org.sakaiproject.service.gradebook.shared.Assignment) i.next(); if (!gAssignment.isExternallyMaintained() || gAssignment.isExternallyMaintained() && gAssignment.getExternalAppName().equals(getToolTitle())) { gradebookAssignmentsExceptSamigo.add(gAssignment); } } context.put("gradebookAssignments", gradebookAssignmentsExceptSamigo); if (StringUtil.trimToNull((String) state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null) { state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); } context.put("withGradebook", Boolean.TRUE); // offer the gradebook integration choice only in the Assignments with Grading tool boolean withGrade = ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(); if (withGrade) { context.put("name_Addtogradebook", AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); context.put("name_AssociateGradebookAssignment", AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); } context.put("gradebookChoice", state.getAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("gradebookChoice_no", AssignmentService.GRADEBOOK_INTEGRATION_NO); context.put("gradebookChoice_add", AssignmentService.GRADEBOOK_INTEGRATION_ADD); context.put("gradebookChoice_associate", AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (associateGradebookAssignment != null) { context.put("associateGradebookAssignment", associateGradebookAssignment); String assignmentId = (String) state.getAttribute(EDIT_ASSIGNMENT_ID); if (assignmentId != null) { try { Assignment a = AssignmentService.getAssignment(assignmentId); context.put("noAddToGradebookChoice", Boolean.valueOf(associateGradebookAssignment.equals(a.getReference()))); } catch (Exception ee) { // ignore } } } } catch (Exception e) { // not able to link to Gradebook Log.warn("chef", this + e.getMessage()); } if (StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)) == null) { state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); } } context.put("monthTable", monthTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String range = StringUtil.trimToNull((String) state.getAttribute(NEW_ASSIGNMENT_RANGE)); if (range != null) { context.put("range", range); } String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // put site object into context try { // get current site Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", site); } catch (Exception ignore) { } if (AssignmentService.getAllowGroupAssignments()) { Collection groupsAllowAddAssignment = AssignmentService.getGroupsAllowAddAssignment(contextString); if (range == null) { if (AssignmentService.allowAddSiteAssignment(contextString)) { // default to make site selection context.put("range", "site"); } else if (groupsAllowAddAssignment.size() > 0) { // to group otherwise context.put("range", "groups"); } } // group list which user can add message to if (groupsAllowAddAssignment.size() > 0) { String sort = (String) state.getAttribute(SORTED_BY); String asc = (String) state.getAttribute(SORTED_ASC); if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION))) { sort = SORTED_BY_GROUP_TITLE; asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sort); state.setAttribute(SORTED_ASC, asc); } context.put("groups", new SortedIterator(groupsAllowAddAssignment.iterator(), new AssignmentComparator(state, sort, asc))); context.put("assignmentGroups", state.getAttribute(NEW_ASSIGNMENT_GROUPS)); } } context.put("allowGroupAssignmentsInGradebook", new Boolean(AssignmentService.getAllowGroupAssignmentsInGradebook())); // the notification email choices if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) != null && ((Boolean) state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS)).booleanValue()) { context.put("name_assignment_instructor_notifications", ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) == null) { // set the notification value using site default state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT)); } context.put("value_assignment_instructor_notifications", state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); // the option values context.put("value_assignment_instructor_notifications_none", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE); context.put("value_assignment_instructor_notifications_each", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH); context.put("value_assignment_instructor_notifications_digest", Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST); } } // setAssignmentFormContext /** * build the instructor view of create a new assignment */ protected String build_instructor_preview_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("time", TimeService.newTime()); context.put("user", UserDirectoryService.getCurrentUser()); context.put("value_Title", (String) state.getAttribute(NEW_ASSIGNMENT_TITLE)); context.put("name_order", NEW_ASSIGNMENT_ORDER); context.put("value_position_order", (String) state.getAttribute(NEW_ASSIGNMENT_ORDER)); Time openTime = getOpenTime(state); context.put("value_OpenDate", openTime); // due time int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue(); int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue(); int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue(); int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue(); int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue(); String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); context.put("value_DueDate", dueTime); // close time Time closeTime = TimeService.newTime(); Boolean enableCloseDate = (Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE); context.put("value_EnableCloseDate", enableCloseDate); if ((enableCloseDate).booleanValue()) { int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); context.put("value_CloseDate", closeTime); } context.put("value_Sections", state.getAttribute(NEW_ASSIGNMENT_SECTION)); context.put("value_SubmissionType", state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)); context.put("value_GradeType", state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)); String maxGrade = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); context.put("value_GradePoints", displayGrade(state, maxGrade)); context.put("value_Description", state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION)); context.put("value_CheckAddDueDate", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); context.put("value_CheckAutoAnnounce", state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); context.put("value_CheckAddHonorPledge", state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE)); // get all available assignments from Gradebook tool except for those created from if (isGradebookDefined()) { context.put("gradebookChoice", state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); context.put("associateGradebookAssignment", state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); } context.put("monthTable", monthTable()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hide_assignment_option_flag", state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG)); context.put("attachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("preview_assignment_assignment_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG)); context.put("preview_assignment_student_view_hide_flag", state.getAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG)); String assignmentId = StringUtil.trimToNull((String) state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID)); if (assignmentId != null) { // editing existing assignment context.put("value_assignment_id", assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); context.put("isDraft", Boolean.valueOf(a.getDraft())); } catch (Exception e) { Log.warn("chef", this + e.getMessage() + assignmentId); } } else { // new assignment context.put("isDraft", Boolean.TRUE); } context.put("value_assignmentcontent_id", state.getAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID)); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_ASSIGNMENT; } // build_instructor_preview_assignment_context /** * build the instructor view to delete an assignment */ protected String build_instructor_delete_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { Vector assignments = new Vector(); Vector assignmentIds = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < assignmentIds.size(); i++) { try { Assignment a = AssignmentService.getAssignment((String) assignmentIds.get(i)); Iterator submissions = AssignmentService.getSubmissions(a).iterator(); if (submissions.hasNext()) { // if there is submission to the assignment, show the alert addAlert(state, rb.getString("areyousur") + " \"" + a.getTitle() + "\" " + rb.getString("whihassub") + "\n"); } assignments.add(a); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } context.put("assignments", assignments); context.put("service", AssignmentService.getInstance()); context.put("currentTime", TimeService.newTime()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_DELETE_ASSIGNMENT; } // build_instructor_delete_assignment_context /** * build the instructor view to grade an submission */ protected String build_instructor_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { int gradeType = -1; // need to show the alert for grading drafts? boolean addGradeDraftAlert = false; // assignment Assignment a = null; try { a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // assignment submission try { AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)); if (s != null) { context.put("submission", s); // show alert if student is working on a draft if (!s.getSubmitted() // not submitted && ((s.getSubmittedText() != null && s.getSubmittedText().length()> 0) // has some text || (s.getSubmittedAttachments() != null && s.getSubmittedAttachments().size() > 0))) // has some attachment { if (s.getCloseTime().after(TimeService.newTime())) { // not pass the close date yet addGradeDraftAlert = true; } else { // passed the close date already addGradeDraftAlert = false; } } ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { context.put("value_allowResubmitNumber", Integer.valueOf((String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER))); String allowResubmitTimeString =p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); Time allowResubmitTime = null; if (allowResubmitTimeString != null) { // if there is a local setting allowResubmitTime = TimeService.newTime(Long.parseLong(allowResubmitTimeString)); } else if (a != null) { // if there is no local setting, default to assignment close time allowResubmitTime = a.getCloseTime(); } // set up related state variables putTimePropertiesInState(state, allowResubmitTime, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM); // put allow resubmit time information into context putTimePropertiesInContext(context, state, "Resubmit", ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN, ALLOW_RESUBMIT_CLOSEAMPM); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } context.put("user", state.getAttribute(STATE_USER)); context.put("submissionTypeTable", submissionTypeTable()); context.put("instructorAttachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // names context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID); context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT); context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); context.put("name_grade", GRADE_SUBMISSION_GRADE); context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // values context.put("value_year_from", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM)); context.put("value_year_to", state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO)); context.put("value_grade_assignment_id", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("value_feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("value_feedback_text", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT)); context.put("value_feedback_attachment", state.getAttribute(ATTACHMENTS)); // format to show one decimal place in grade context.put("value_grade", (gradeType == 3) ? displayGrade(state, (String) state.getAttribute(GRADE_SUBMISSION_GRADE)) : state.getAttribute(GRADE_SUBMISSION_GRADE)); context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG)); context.put("gradingAttachments", state.getAttribute(ATTACHMENTS)); // is this a non-electronic submission type of assignment context.put("nonElectronic", (a!=null && a.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION)?Boolean.TRUE:Boolean.FALSE); if (addGradeDraftAlert) { addAlert(state, rb.getString("grading.alert.draft.beforeclosedate")); } context.put("alertGradeDraft", Boolean.valueOf(addGradeDraftAlert)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_SUBMISSION; } // build_instructor_grade_submission_context /** * Parse time value and put corresponding values into state * @param context * @param state * @param a * @param timeValue * @param timeName * @param month * @param day * @param year * @param hour * @param min * @param ampm */ private void putTimePropertiesInState(SessionState state, Time timeValue, String month, String day, String year, String hour, String min, String ampm) { TimeBreakdown bTime = timeValue.breakdownLocal(); state.setAttribute(month, new Integer(bTime.getMonth())); state.setAttribute(day, new Integer(bTime.getDay())); state.setAttribute(year, new Integer(bTime.getYear())); int bHour = bTime.getHour(); if (bHour >= 12) { state.setAttribute(ampm, "PM"); } else { state.setAttribute(ampm, "AM"); } if (bHour == 0) { // for midnight point, we mark it as 12AM bHour = 12; } state.setAttribute(hour, new Integer((bHour > 12) ? bHour - 12 : bHour)); state.setAttribute(min, new Integer(bTime.getMin())); } /** * put related time information into context variable * @param context * @param state * @param timeName * @param month * @param day * @param year * @param hour * @param min * @param ampm */ private void putTimePropertiesInContext(Context context, SessionState state, String timeName, String month, String day, String year, String hour, String min, String ampm) { // get the submission level of close date setting context.put("name_" + timeName + "Month", month); context.put("name_" + timeName + "Day", day); context.put("name_" + timeName + "Year", year); context.put("name_" + timeName + "Hour", hour); context.put("name_" + timeName + "Min", min); context.put("name_" + timeName + "AMPM", ampm); context.put("value_" + timeName + "Month", (Integer) state.getAttribute(month)); context.put("value_" + timeName + "Day", (Integer) state.getAttribute(day)); context.put("value_" + timeName + "Year", (Integer) state.getAttribute(year)); context.put("value_" + timeName + "AMPM", (String) state.getAttribute(ampm)); context.put("value_" + timeName + "Hour", (Integer) state.getAttribute(hour)); context.put("value_" + timeName + "Min", (Integer) state.getAttribute(min)); } private List getPrevFeedbackAttachments(ResourceProperties p) { String attachmentsString = p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS); String[] attachmentsReferences = attachmentsString.split(","); List prevFeedbackAttachments = EntityManager.newReferenceList(); for (int k =0; k < attachmentsReferences.length; k++) { prevFeedbackAttachments.add(EntityManager.newReference(attachmentsReferences[k])); } return prevFeedbackAttachments; } /** * build the instructor preview of grading submission */ protected String build_instructor_preview_grade_submission_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // assignment int gradeType = -1; try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); context.put("assignment", a); gradeType = a.getContent().getTypeOfGrade(); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } // submission try { context.put("submission", AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID))); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } User user = (User) state.getAttribute(STATE_USER); context.put("user", user); context.put("submissionTypeTable", submissionTypeTable()); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // filter the feedback text for the instructor comment and mark it as red String feedbackText = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("feedback_comment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); context.put("feedback_text", feedbackText); context.put("feedback_attachment", state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT)); // format to show one decimal place String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); if (gradeType == 3) { grade = displayGrade(state, grade); } context.put("grade", grade); context.put("comment_open", COMMENT_OPEN); context.put("comment_close", COMMENT_CLOSE); context.put("allowResubmitNumber", state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); String closeTimeString =(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); if (closeTimeString != null) { // close time for resubmit Time time = TimeService.newTime(Long.parseLong(closeTimeString)); context.put("allowResubmitCloseTime", time.toStringLocalFull()); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION; } // build_instructor_preview_grade_submission_context /** * build the instructor view to grade an assignment */ protected String build_instructor_grade_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("user", state.getAttribute(STATE_USER)); // sorting related fields context.put("sortedBy", state.getAttribute(SORTED_GRADE_SUBMISSION_BY)); context.put("sortedAsc", state.getAttribute(SORTED_GRADE_SUBMISSION_ASC)); context.put("sort_lastName", SORTED_GRADE_SUBMISSION_BY_LASTNAME); context.put("sort_submitTime", SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME); context.put("sort_submitStatus", SORTED_GRADE_SUBMISSION_BY_STATUS); context.put("sort_submitGrade", SORTED_GRADE_SUBMISSION_BY_GRADE); context.put("sort_submitReleased", SORTED_GRADE_SUBMISSION_BY_RELEASED); context.put("sort_submitReview", SORTED_GRADE_SUBMISSION_CONTENTREVIEW); Assignment assignment = null; try { assignment = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); context.put("assignment", assignment); state.setAttribute(EXPORT_ASSIGNMENT_ID, assignment.getId()); // ever set the default grade for no-submissions String defaultGrade = assignment.getProperties().getProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE); if (defaultGrade != null) { context.put("defaultGrade", defaultGrade); } // groups if (state.getAttribute(VIEW_SUBMISSION_LIST_OPTION) == null) { state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, rb.getString("gen.viewallgroupssections")); } String view = (String)state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); context.put("view", view); // access point url for zip file download String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String accessPointUrl = ServerConfigurationService.getAccessUrl().concat(AssignmentService.submissionsZipReference( contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF))); if (!view.equals(rb.getString("gen.viewallgroupssections"))) { // append the group info to the end accessPointUrl = accessPointUrl.concat(view); } context.put("accessPointUrl", accessPointUrl); if (AssignmentService.getAllowGroupAssignments()) { Collection groupsAllowGradeAssignment = AssignmentService.getGroupsAllowGradeAssignment((String) state.getAttribute(STATE_CONTEXT_STRING), assignment.getReference()); // group list which user can add message to if (groupsAllowGradeAssignment.size() > 0) { String sort = (String) state.getAttribute(SORTED_BY); String asc = (String) state.getAttribute(SORTED_ASC); if (sort == null || (!sort.equals(SORTED_BY_GROUP_TITLE) && !sort.equals(SORTED_BY_GROUP_DESCRIPTION))) { sort = SORTED_BY_GROUP_TITLE; asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_BY, sort); state.setAttribute(SORTED_ASC, asc); } context.put("groups", new SortedIterator(groupsAllowGradeAssignment.iterator(), new AssignmentComparator(state, sort, asc))); } } // for non-electronic assignment if (assignment.getContent() != null && assignment.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { updateNonElectronicSubmissions(state, assignment); } List userSubmissions = prepPage(state); state.setAttribute(USER_SUBMISSIONS, userSubmissions); context.put("userSubmissions", state.getAttribute(USER_SUBMISSIONS)); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { context.put("producer", ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer")); addProviders(context, state); addActivity(context, assignment); context.put("taggable", Boolean.valueOf(true)); } context.put("submissionTypeTable", submissionTypeTable()); context.put("attachments", state.getAttribute(ATTACHMENTS)); // Get turnitin results for instructors context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); context.put("assignment_expand_flag", state.getAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG)); context.put("submission_expand_flag", state.getAttribute(GRADE_SUBMISSION_EXPAND_FLAG)); // the user directory service context.put("userDirectoryService", UserDirectoryService.getInstance()); add2ndToolbarFields(data, context); pagingInfoToContext(state, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_GRADE_ASSIGNMENT; } // build_instructor_grade_assignment_context /** * Synchronize the submissions for non electronic assignment with the current user set * @param state * @param assignment */ private void updateNonElectronicSubmissions(SessionState state, Assignment assignment) { List submissions = AssignmentService.getSubmissions(assignment); // the following operation is accessible for those with add assignment right List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers(assignment.getReference()); HashSet<String> submittersIdSet = getSubmittersIdSet(submissions); HashSet<String> allowAddSubmissionUsersIdSet = getAllowAddSubmissionUsersIdSet(allowAddSubmissionUsers); if (!submittersIdSet.equals(allowAddSubmissionUsersIdSet)) { // get the difference between two sets try { HashSet<String> addSubmissionUserIdSet = (HashSet<String>) allowAddSubmissionUsersIdSet.clone(); addSubmissionUserIdSet.removeAll(submittersIdSet); HashSet<String> removeSubmissionUserIdSet = (HashSet<String>) submittersIdSet.clone(); removeSubmissionUserIdSet.removeAll(allowAddSubmissionUsersIdSet); try { addRemoveSubmissionsForNonElectronicAssignment(state, submissions, addSubmissionUserIdSet, removeSubmissionUserIdSet, assignment); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } catch (Exception e) { Log.warn("chef", this + e.getMessage()); } } } /** * build the instructor view of an assignment */ protected String build_instructor_view_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("tlang", rb); Assignment assignment = null; try { assignment = AssignmentService.getAssignment((String) state.getAttribute(VIEW_ASSIGNMENT_ID)); context.put("assignment", assignment); // the creator String creatorId = assignment.getCreator(); try { User creator = UserDirectoryService.getUser(creatorId); context.put("creator", creator.getDisplayName()); } catch (Exception ee) { context.put("creator", creatorId); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); if (taggingManager.isTaggable() && assignment != null) { List<DecoratedTaggingProvider> providers = addProviders(context, state); List<TaggingHelperInfo> activityHelpers = new ArrayList<TaggingHelperInfo>(); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); for (DecoratedTaggingProvider provider : providers) { TaggingHelperInfo helper = provider.getProvider() .getActivityHelperInfo( assignmentActivityProducer.getActivity( assignment).getReference()); if (helper != null) { activityHelpers.add(helper); } } addActivity(context, assignment); context.put("activityHelpers", activityHelpers); context.put("taggable", Boolean.valueOf(true)); } context.put("currentTime", TimeService.newTime()); context.put("submissionTypeTable", submissionTypeTable()); context.put("hideAssignmentFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG)); context.put("hideStudentViewFlag", state.getAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_ASSIGNMENT; } // build_instructor_view_assignment_context /** * build the instructor view of reordering assignments */ protected String build_instructor_reorder_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); List assignments = prepPage(state); context.put("assignments", assignments.iterator()); context.put("assignmentsize", assignments.size()); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); context.put("sortedBy", sortedBy); context.put("sortedAsc", sortedAsc); // put site object into context try { // get current site Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); context.put("site", site); } catch (Exception ignore) { } context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("userDirectoryService", UserDirectoryService.getInstance()); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REORDER_ASSIGNMENT; } // build_instructor_reorder_assignment_context /** * build the instructor view to view the list of students for an assignment */ protected String build_instructor_view_students_assignment_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // get the realm and its member List studentMembers = new Vector(); List allowSubmitMembers = AssignmentService.allowAddAnySubmissionUsers(contextString); for (Iterator allowSubmitMembersIterator=allowSubmitMembers.iterator(); allowSubmitMembersIterator.hasNext();) { // get user try { String userId = (String) allowSubmitMembersIterator.next(); User user = UserDirectoryService.getUser(userId); studentMembers.add(user); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } context.put("studentMembers", new SortedIterator(studentMembers.iterator(), new AssignmentComparator(state, SORTED_USER_BY_SORTNAME, Boolean.TRUE.toString()))); context.put("assignmentService", AssignmentService.getInstance()); Hashtable showStudentAssignments = new Hashtable(); if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) != null) { Set showStudentListSet = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); context.put("studentListShowSet", showStudentListSet); for (Iterator showStudentListSetIterator=showStudentListSet.iterator(); showStudentListSetIterator.hasNext();) { // get user try { String userId = (String) showStudentListSetIterator.next(); User user = UserDirectoryService.getUser(userId); // sort the assignments into the default order before adding Iterator assignmentSorter = AssignmentService.getAssignmentsForContext(contextString, userId); // filter to obtain only grade-able assignments List rv = new Vector(); while (assignmentSorter.hasNext()) { Assignment a = (Assignment) assignmentSorter.next(); if (AssignmentService.allowGradeSubmission(a.getReference())) { rv.add(a); } } Iterator assignmentSortFinal = new SortedIterator(rv.iterator(), new AssignmentComparator(state, SORTED_BY_DEFAULT, Boolean.TRUE.toString())); showStudentAssignments.put(user, assignmentSortFinal); } catch (Exception ee) { Log.warn("chef", this + ee.getMessage()); } } } context.put("studentAssignmentsTable", showStudentAssignments); add2ndToolbarFields(data, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT; } // build_instructor_view_students_assignment_context /** * build the instructor view to report the submissions */ protected String build_instructor_report_submissions(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("submissions", prepPage(state)); context.put("sortedBy", (String) state.getAttribute(SORTED_SUBMISSION_BY)); context.put("sortedAsc", (String) state.getAttribute(SORTED_SUBMISSION_ASC)); context.put("sortedBy_lastName", SORTED_SUBMISSION_BY_LASTNAME); context.put("sortedBy_submitTime", SORTED_SUBMISSION_BY_SUBMIT_TIME); context.put("sortedBy_grade", SORTED_SUBMISSION_BY_GRADE); context.put("sortedBy_status", SORTED_SUBMISSION_BY_STATUS); context.put("sortedBy_released", SORTED_SUBMISSION_BY_RELEASED); context.put("sortedBy_assignment", SORTED_SUBMISSION_BY_ASSIGNMENT); context.put("sortedBy_maxGrade", SORTED_SUBMISSION_BY_MAX_GRADE); add2ndToolbarFields(data, context); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("accessPointUrl", ServerConfigurationService.getAccessUrl() + AssignmentService.gradesSpreadsheetReference(contextString, null)); pagingInfoToContext(state, context); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_REPORT_SUBMISSIONS; } // build_instructor_report_submissions // Is Gradebook defined for the site? protected boolean isGradebookDefined() { boolean rv = false; try { GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager .get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); if (g.isGradebookDefined(gradebookUid)) { rv = true; } } catch (Exception e) { Log.debug("chef", this + rb.getString("addtogradebook.alertMessage") + "\n" + e.getMessage()); } return rv; } // isGradebookDefined() /** * build the instructor view to upload information from archive file */ protected String build_instructor_upload_all(VelocityPortlet portlet, Context context, RunData data, SessionState state) { context.put("hasSubmissionText", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT)); context.put("hasSubmissionAttachment", state.getAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT)); context.put("hasGradeFile", state.getAttribute(UPLOAD_ALL_HAS_GRADEFILE)); context.put("hasComments", state.getAttribute(UPLOAD_ALL_HAS_COMMENTS)); context.put("hasFeedbackText", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT)); context.put("hasFeedbackAttachment", state.getAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT)); context.put("releaseGrades", state.getAttribute(UPLOAD_ALL_RELEASE_GRADES)); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); context.put("accessPointUrl", (ServerConfigurationService.getAccessUrl()).concat(AssignmentService.submissionsZipReference( contextString, (String) state.getAttribute(EXPORT_ASSIGNMENT_REF)))); String template = (String) getContext(data).get("template"); return template + TEMPLATE_INSTRUCTOR_UPLOAD_ALL; } // build_instructor_upload_all /** ** Retrieve tool title from Tool configuration file or use default ** (This should return i18n version of tool title if available) **/ private String getToolTitle() { Tool tool = ToolManager.getTool(ASSIGNMENT_TOOL_ID); String toolTitle = null; if (tool == null) toolTitle = "Assignments"; else toolTitle = tool.getTitle(); return toolTitle; } /** * integration with gradebook * * @param state * @param assignmentRef Assignment reference * @param associateGradebookAssignment The title for the associated GB assignment * @param addUpdateRemoveAssignment "add" for adding the assignment; "update" for updating the assignment; "remove" for remove assignment * @param oldAssignment_title The original assignment title * @param newAssignment_title The updated assignment title * @param newAssignment_maxPoints The maximum point of the assignment * @param newAssignment_dueTime The due time of the assignment * @param submissionRef Any submission grade need to be updated? Do bulk update if null * @param updateRemoveSubmission "update" for update submission;"remove" for remove submission */ protected void integrateGradebook (SessionState state, String assignmentRef, String associateGradebookAssignment, String addUpdateRemoveAssignment, String oldAssignment_title, String newAssignment_title, int newAssignment_maxPoints, Time newAssignment_dueTime, String submissionRef, String updateRemoveSubmission) { associateGradebookAssignment = StringUtil.trimToNull(associateGradebookAssignment); // add or remove external grades to gradebook // a. if Gradebook does not exists, do nothing, 'cos setting should have been hidden // b. if Gradebook exists, just call addExternal and removeExternal and swallow any exception. The // exception are indication that the assessment is already in the Gradebook or there is nothing // to remove. String assignmentToolTitle = getToolTitle(); GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); if (g.isGradebookDefined(gradebookUid)) { boolean isExternalAssignmentDefined=g.isExternalAssignmentDefined(gradebookUid, assignmentRef); boolean isExternalAssociateAssignmentDefined = g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment); boolean isAssignmentDefined = g.isAssignmentDefined(gradebookUid, associateGradebookAssignment); if (addUpdateRemoveAssignment != null) { // add an entry into Gradebook for newly created assignment or modified assignment, and there wasn't a correspond record in gradebook yet if ((addUpdateRemoveAssignment.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD) || (addUpdateRemoveAssignment.equals("update") && !isExternalAssignmentDefined)) && associateGradebookAssignment == null) { // add assignment into gradebook try { // add assignment to gradebook g.addExternalAssessment(gradebookUid, assignmentRef, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime()), assignmentToolTitle); } catch (AssignmentHasIllegalPointsException e) { addAlert(state, rb.getString("addtogradebook.illegalPoints")); } catch (ConflictingAssignmentNameException e) { // add alert prompting for change assignment title addAlert(state, rb.getString("addtogradebook.nonUniqueTitle")); } catch (ConflictingExternalIdException e) { // this shouldn't happen, as we have already checked for assignment reference before. Log the error Log.warn("chef", this + e.getMessage()); } catch (GradebookNotFoundException e) { // this shouldn't happen, as we have checked for gradebook existence before Log.warn("chef", this + e.getMessage()); } catch (Exception e) { // ignore Log.warn("chef", this + e.getMessage()); } } else if (addUpdateRemoveAssignment.equals("update")) { if (associateGradebookAssignment != null && isExternalAssociateAssignmentDefined) { // if there is an external entry created in Gradebook based on this assignment, update it try { Assignment a = AssignmentService.getAssignment(associateGradebookAssignment); // update attributes if the GB assignment was created for the assignment g.updateExternalAssessment(gradebookUid, associateGradebookAssignment, null, newAssignment_title, newAssignment_maxPoints/10.0, new Date(newAssignment_dueTime.getTime())); } catch(Exception e) { Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage()); } } } // addUpdateRemove != null else if (addUpdateRemoveAssignment.equals("remove")) { // remove assignment and all submission grades removeNonAssociatedExternalGradebookEntry((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentRef, associateGradebookAssignment, g, gradebookUid); } } if (updateRemoveSubmission != null) { try { Assignment a = AssignmentService.getAssignment(assignmentRef); if (updateRemoveSubmission.equals("update") && a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null && !a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK).equals(AssignmentService.GRADEBOOK_INTEGRATION_NO) && a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { if (submissionRef == null) { // bulk add all grades for assignment into gradebook Iterator submissions = AssignmentService.getSubmissions(a).iterator(); Map m = new HashMap(); // any score to copy over? get all the assessmentGradingData and copy over while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); if (aSubmission.getGradeReleased()) { User[] submitters = aSubmission.getSubmitters(); String submitterId = submitters[0].getId(); String gradeString = StringUtil.trimToNull(aSubmission.getGrade()); Double grade = gradeString != null ? Double.valueOf(displayGrade(state,gradeString)) : null; m.put(submitterId, grade); } } // need to update only when there is at least one submission if (m.size()>0) { if (associateGradebookAssignment != null) { if (isExternalAssociateAssignmentDefined) { // the associated assignment is externally maintained g.updateExternalAssessmentScores(gradebookUid, associateGradebookAssignment, m); } else if (isAssignmentDefined) { // the associated assignment is internal one, update records one by one submissions = AssignmentService.getSubmissions(a).iterator(); while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); User[] submitters = aSubmission.getSubmitters(); String submitterId = submitters[0].getId(); String gradeString = StringUtil.trimToNull(aSubmission.getGrade()); Double grade = (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null; g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitterId, grade, assignmentToolTitle); } } } else if (isExternalAssignmentDefined) { g.updateExternalAssessmentScores(gradebookUid, assignmentRef, m); } } } else { try { // only update one submission AssignmentSubmission aSubmission = (AssignmentSubmission) AssignmentService .getSubmission(submissionRef); User[] submitters = aSubmission.getSubmitters(); String gradeString = StringUtil.trimToNull(aSubmission.getGrade()); if (associateGradebookAssignment != null) { if (g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment)) { // the associated assignment is externally maintained g.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null); } else if (g.isAssignmentDefined(gradebookUid, associateGradebookAssignment)) { // the associated assignment is internal one, update records g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null, assignmentToolTitle); } } else { g.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(), (gradeString != null && aSubmission.getGradeReleased()) ? Double.valueOf(displayGrade(state,gradeString)) : null); } } catch (Exception e) { Log.warn("chef", "Cannot find submission " + submissionRef + ": " + e.getMessage()); } } } else if (updateRemoveSubmission.equals("remove")) { if (submissionRef == null) { // remove all submission grades (when changing the associated entry in Gradebook) Iterator submissions = AssignmentService.getSubmissions(a).iterator(); // any score to copy over? get all the assessmentGradingData and copy over while (submissions.hasNext()) { AssignmentSubmission aSubmission = (AssignmentSubmission) submissions.next(); User[] submitters = aSubmission.getSubmitters(); if (isExternalAssociateAssignmentDefined) { // if the old associated assignment is an external maintained one g.updateExternalAssessmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null); } else if (isAssignmentDefined) { g.setAssignmentScore(gradebookUid, associateGradebookAssignment, submitters[0].getId(), null, assignmentToolTitle); } } } else { // remove only one submission grade try { AssignmentSubmission aSubmission = (AssignmentSubmission) AssignmentService .getSubmission(submissionRef); User[] submitters = aSubmission.getSubmitters(); g.updateExternalAssessmentScore(gradebookUid, assignmentRef, submitters[0].getId(), null); } catch (Exception e) { Log.warn("chef", "Cannot find submission " + submissionRef + ": " + e.getMessage()); } } } } catch (Exception e) { Log.warn("chef", rb.getString("cannot_find_assignment") + assignmentRef + ": " + e.getMessage()); } } // updateRemoveSubmission != null } } // integrateGradebook /** * Go to the instructor view */ public void doView_instructor(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doView_instructor /** * Go to the student view */ public void doView_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // to the student list of assignment view state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doView_student /** * Action is to view the content of one specific assignment submission */ public void doView_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); String assignmentReference = params.getString("assignmentReference"); state.setAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE, assignmentReference); User u = (User) state.getAttribute(STATE_USER); try { AssignmentSubmission submission = AssignmentService.getSubmission(assignmentReference, u); if (submission != null) { state.setAttribute(VIEW_SUBMISSION_TEXT, submission.getSubmittedText()); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, (new Boolean(submission.getHonorPledgeFlag())).toString()); List v = EntityManager.newReferenceList(); Iterator l = submission.getSubmittedAttachments().iterator(); while (l.hasNext()) { v.add(l.next()); } state.setAttribute(ATTACHMENTS, v); } else { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // try } // doView_submission /** * Action is to view the content of one specific assignment submission */ public void doView_submission_list_option(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String view = params.getString("view"); state.setAttribute(VIEW_SUBMISSION_LIST_OPTION, view); } // doView_submission_list_option /** * Preview of the submission */ public void doPreview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // String assignmentId = params.getString(assignmentId); state.setAttribute(PREVIEW_SUBMISSION_ASSIGNMENT_REFERENCE, state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE)); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(PREVIEW_SUBMISSION_TEXT, text); state.setAttribute(VIEW_SUBMISSION_TEXT, text); // assign the honor pledge attribute String honor_pledge_yes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honor_pledge_yes == null) { honor_pledge_yes = "false"; } state.setAttribute(PREVIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honor_pledge_yes); state.setAttribute(PREVIEW_SUBMISSION_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_PREVIEW_SUBMISSION); } } // doPreview_submission /** * Preview of the grading of submission */ public void doPreview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read user input readGradeForm(data, state, "read"); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION); } } // doPreview_grade_submission /** * Action is to end the preview submission process */ public void doDone_preview_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION); } // doDone_preview_submission /** * Action is to end the view assignment process */ public void doDone_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doDone_view_assignments /** * Action is to end the preview new assignment process */ public void doDone_preview_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the new assignment page state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doDone_preview_new_assignment /** * Action is to end the user view assignment process and redirect him to the assignment list view */ public void doCancel_student_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_student_view_assignment /** * Action is to end the show submission process */ public void doCancel_show_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view assignment state.setAttribute(VIEW_ASSIGNMENT_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_show_submission /** * Action is to cancel the delete assignment process */ public void doCancel_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the show assignment object state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); // back to the instructor list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_delete_assignment /** * Action is to end the show submission process */ public void doCancel_edit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset sorting setDefaultSort(state); } // doCancel_edit_assignment /** * Action is to end the show submission process */ public void doCancel_new_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object resetAssignment(state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset sorting setDefaultSort(state); } // doCancel_new_assignment /** * Action is to cancel the grade submission process */ public void doCancel_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the assignment object // resetAssignment (state); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } // doCancel_grade_submission /** * Action is to cancel the preview grade process */ public void doCancel_preview_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } // doCancel_preview_grade_submission /** * Action is to cancel the reorder process */ public void doCancel_reorder(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_reorder /** * Action is to cancel the preview grade process */ public void doCancel_preview_to_list_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the instructor view of grading a submission state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } // doCancel_preview_to_list_submission /** * Action is to return to the view of list assignments */ public void doList_assignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doList_assignments /** * Action is to cancel the student view grade process */ public void doCancel_view_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the view grade submission id state.setAttribute(VIEW_GRADE_SUBMISSION_ID, ""); // back to the student list view of assignments state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } // doCancel_view_grade /** * Action is to save the grade to submission */ public void doSave_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "save"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "save"); } } // doSave_grade_submission /** * Action is to release the grade to submission */ public void doRelease_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "release"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "release"); } } // doRelease_grade_submission /** * Action is to return submission with or without grade */ public void doReturn_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); readGradeForm(data, state, "return"); if (state.getAttribute(STATE_MESSAGE) == null) { grade_submission_option(data, "return"); } } // doReturn_grade_submission /** * Action is to return submission with or without grade from preview */ public void doReturn_preview_grade_submission(RunData data) { grade_submission_option(data, "return"); } // doReturn_grade_preview_submission /** * Action is to save submission with or without grade from preview */ public void doSave_preview_grade_submission(RunData data) { grade_submission_option(data, "save"); } // doSave_grade_preview_submission /** * Common grading routine plus specific operation to differenciate cases when saving, releasing or returning grade. */ private void grade_submission_option(RunData data, String gradeOption) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue(): false; String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); try { // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(sId); Assignment a = sEdit.getAssignment(); int typeOfGrade = a.getContent().getTypeOfGrade(); if (!withGrade) { // no grade input needed for the without-grade version of assignment tool sEdit.setGraded(true); if (gradeOption.equals("return") || gradeOption.equals("release")) { sEdit.setGradeReleased(true); } } else if (grade == null) { sEdit.setGrade(""); sEdit.setGraded(false); sEdit.setGradeReleased(false); } else { if (typeOfGrade == 1) { sEdit.setGrade(rb.getString("gen.nograd")); } else { sEdit.setGrade(grade); } if (grade.length() != 0) { sEdit.setGraded(true); } else { sEdit.setGraded(false); } } if (gradeOption.equals("release")) { sEdit.setGradeReleased(true); sEdit.setGraded(true); // clear the returned flag sEdit.setReturned(false); sEdit.setTimeReturned(null); } else if (gradeOption.equals("return")) { sEdit.setGradeReleased(true); sEdit.setGraded(true); sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); } else if (gradeOption.equals("save")) { sEdit.setGradeReleased(false); sEdit.setReturned(false); sEdit.setTimeReturned(null); } if (state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // get resubmit number ResourcePropertiesEdit pEdit = sEdit.getPropertiesEdit(); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR) != null) { // get resubmit time Time closeTime = getAllowSubmitCloseTime(state); pEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); } else { pEdit.removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } // the instructor comment String feedbackCommentString = StringUtil .trimToNull((String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT)); if (feedbackCommentString != null) { sEdit.setFeedbackComment(feedbackCommentString); } // the instructor inline feedback String feedbackTextString = (String) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT); if (feedbackTextString != null) { sEdit.setFeedbackText(feedbackTextString); } List v = (List) state.getAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); if (v != null) { // clear the old attachments first sEdit.clearFeedbackAttachments(); for (int i = 0; i < v.size(); i++) { sEdit.addFeedbackAttachment((Reference) v.get(i)); } } String sReference = sEdit.getReference(); AssignmentService.commitEdit(sEdit); // update grades in gradebook String aReference = a.getReference(); String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); if (gradeOption.equals("release") || gradeOption.equals("return")) { // update grade in gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update"); } else { // remove grade from gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "remove"); } } catch (IdUnusedException e) { } catch (PermissionException e) { } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } // try if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } } // grade_submission_option /** * Action is to save the submission as a draft */ public void doSave_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = "false"; } String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); User u = (User) state.getAttribute(STATE_USER); if (state.getAttribute(STATE_MESSAGE) == null) { try { Assignment a = AssignmentService.getAssignment(aReference); String assignmentId = a.getId(); AssignmentSubmission submission = AssignmentService.getSubmission(aReference, u); if (submission != null) { // the submission already exists, change the text and honor pledge value, save as draft try { AssignmentSubmissionEdit edit = AssignmentService.editSubmission(submission.getReference()); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setSubmitted(false); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // clear the old attachments first edit.clearSubmittedAttachments(); // add each new attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle()); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot12")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } else { // new submission, save as draft try { AssignmentSubmissionEdit edit = AssignmentService.addSubmission((String) state .getAttribute(STATE_CONTEXT_STRING), assignmentId, SessionManager.getCurrentSessionUserId()); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setSubmitted(false); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(edit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot4")); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION); } } // doSave_submission /** * Action is to post the submission */ public void doPost_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String aReference = (String) state.getAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); Assignment a = null; try { a = AssignmentService.getAssignment(aReference); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } if (AssignmentService.canSubmit(contextString, a)) { ParameterParser params = data.getParameters(); // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); if (text == null) { text = (String) state.getAttribute(VIEW_SUBMISSION_TEXT); } else { state.setAttribute(VIEW_SUBMISSION_TEXT, text); } String honorPledgeYes = params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES); if (honorPledgeYes == null) { honorPledgeYes = (String) state.getAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES); } if (honorPledgeYes == null) { honorPledgeYes = "false"; } User u = (User) state.getAttribute(STATE_USER); String assignmentId = ""; if (state.getAttribute(STATE_MESSAGE) == null) { assignmentId = a.getId(); if (a.getContent().getHonorPledge() != 1) { if (!Boolean.valueOf(honorPledgeYes).booleanValue()) { addAlert(state, rb.getString("youarenot18")); } state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, honorPledgeYes); } // check the submission inputs based on the submission type int submissionType = a.getContent().getTypeOfSubmission(); if (submissionType == 1) { // for the inline only submission if (text.length() == 0) { addAlert(state, rb.getString("youmust7")); } } else if (submissionType == 2) { // for the attachment only submission Vector v = (Vector) state.getAttribute(ATTACHMENTS); if ((v == null) || (v.size() == 0)) { addAlert(state, rb.getString("youmust1")); } } else if (submissionType == 3) { // for the inline and attachment submission Vector v = (Vector) state.getAttribute(ATTACHMENTS); if ((text.length() == 0) && ((v == null) || (v.size() == 0))) { addAlert(state, rb.getString("youmust2")); } } } if ((state.getAttribute(STATE_MESSAGE) == null) && (a != null)) { try { AssignmentSubmission submission = AssignmentService.getSubmission(a.getReference(), u); if (submission != null) { // the submission already exists, change the text and honor pledge value, post it try { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setSubmittedText(text); sEdit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); sEdit.setTimeSubmitted(TimeService.newTime()); sEdit.setSubmitted(true); // for resubmissions // when resubmit, keep the Returned flag on till the instructor grade again. Time now = TimeService.newTime(); ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit(); if (sEdit.getGraded()) { // add the current grade into previous grade histroy String previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES); if (previousGrades == null) { previousGrades = (String) sEdit.getProperties().getProperty( ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); if (previousGrades != null) { int typeOfGrade = a.getContent().getTypeOfGrade(); if (typeOfGrade == 3) { // point grade assignment type // some old unscaled grades, need to scale the number and remove the old property String[] grades = StringUtil.split(previousGrades, " "); String newGrades = ""; for (int jj = 0; jj < grades.length; jj++) { String grade = grades[jj]; if (grade.indexOf(".") == -1) { // show the grade with decimal point grade = grade.concat(".0"); } newGrades = newGrades.concat(grade + " "); } previousGrades = newGrades; } sPropertiesEdit.removeProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_GRADES); } else { previousGrades = ""; } } previousGrades = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />" + sEdit.getGradeDisplay() + "<p />" +previousGrades; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_SCALED_PREVIOUS_GRADES, previousGrades); // clear the current grade and make the submission ungraded sEdit.setGraded(false); sEdit.setGrade(""); sEdit.setGradeReleased(false); // keep the history of assignment feed back text String feedbackTextHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) : ""; feedbackTextHistory = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />" + sEdit.getFeedbackText() + "<p />" + feedbackTextHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT, feedbackTextHistory); // keep the history of assignment feed back comment String feedbackCommentHistory = sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null ? sPropertiesEdit .getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) : ""; feedbackCommentHistory = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />" + sEdit.getFeedbackComment() + "<p />" + feedbackCommentHistory; sPropertiesEdit.addProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT, feedbackCommentHistory); // keep the history of assignment feed back comment String feedbackAttachmentHistory = sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null ? sPropertiesEdit .getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) : ""; List feedbackAttachments = sEdit.getFeedbackAttachments(); String att = rb.getString("gen.subm6") + now.toStringLocalFull() + "<p />"; for (int k = 0; k<feedbackAttachments.size();k++) { att = att + ((Reference) feedbackAttachments.get(k)).getReference() + "<p />"; } feedbackAttachmentHistory = att + feedbackAttachmentHistory; sPropertiesEdit.addProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS, feedbackAttachmentHistory); // reset the previous grading context sEdit.setFeedbackText(""); sEdit.setFeedbackComment(""); sEdit.clearFeedbackAttachments(); // decrease the allow_resubmit_number if (sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { int number = Integer.parseInt(sPropertiesEdit.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); // minus 1 from the submit number if (number>=1) { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(number-1)); } else if (number == -1) { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, String.valueOf(-1)); } } } sEdit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { //Post the attachments before clearing so that we don't sumbit duplicate attachments //Check if we need to post the attachments if (a.getContent().getAllowReviewService()) { if (!attachments.isEmpty()) { sEdit.postAttachment(attachments); } } // clear the old attachments first sEdit.clearSubmittedAttachments(); // add each new attachment Iterator it = attachments.iterator(); while (it.hasNext()) { sEdit.addSubmittedAttachment((Reference) it.next()); } } AssignmentService.commitEdit(sEdit); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin2") + " " + a.getTitle()); } catch (PermissionException e) { addAlert(state, rb.getString("no_permissiion_to_edit_submission")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } else { // new submission, post it try { AssignmentSubmissionEdit edit = AssignmentService.addSubmission(contextString, assignmentId, SessionManager.getCurrentSessionUserId()); edit.setSubmittedText(text); edit.setHonorPledgeFlag(Boolean.valueOf(honorPledgeYes).booleanValue()); edit.setTimeSubmitted(TimeService.newTime()); edit.setSubmitted(true); edit.setAssignment(a); // add attachments List attachments = (List) state.getAttribute(ATTACHMENTS); if (attachments != null) { // add each attachment if ((!attachments.isEmpty()) && a.getContent().getAllowReviewService()) edit.postAttachment(attachments); // add each attachment Iterator it = attachments.iterator(); while (it.hasNext()) { edit.addSubmittedAttachment((Reference) it.next()); } } // get the assignment setting for resubmitting if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { edit.getPropertiesEdit().addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); } AssignmentService.commitEdit(edit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot13")); } } // if -else } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } } // if if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_SUBMISSION_CONFIRMATION); } } // if } // doPost_submission /** * Action is to confirm the submission and return to list view */ public void doConfirm_assignment_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); } /** * Action is to show the new assignment screen */ public void doNew_assignment(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAddAssignment((String) state.getAttribute(STATE_CONTEXT_STRING))) { resetAssignment(state); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot2")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } } // doNew_Assignment /** * Action is to show the reorder assignment screen */ public void doReorder(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // this insures the default order is loaded into the reordering tool state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); if (!alertGlobalNavigation(state, data)) { if (AssignmentService.allowAllGroups((String) state.getAttribute(STATE_CONTEXT_STRING))) { resetAssignment(state); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REORDER_ASSIGNMENT); } else { addAlert(state, rb.getString("youarenot19")); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } } // doReorder /** * Action is to save the input infos for assignment fields * * @param validify * Need to validify the inputs or not */ protected void setNewAssignmentParameters(RunData data, boolean validify) { // read the form inputs SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // put the input value into the state attributes String title = params.getString(NEW_ASSIGNMENT_TITLE); state.setAttribute(NEW_ASSIGNMENT_TITLE, title); String order = params.getString(NEW_ASSIGNMENT_ORDER); state.setAttribute(NEW_ASSIGNMENT_ORDER, order); if (title.length() == 0) { // empty assignment title addAlert(state, rb.getString("plespethe1")); } // open time int openMonth = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openMonth)); int openDay = (new Integer(params.getString(NEW_ASSIGNMENT_OPENDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openDay)); int openYear = (new Integer(params.getString(NEW_ASSIGNMENT_OPENYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openYear)); int openHour = (new Integer(params.getString(NEW_ASSIGNMENT_OPENHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(openHour)); int openMin = (new Integer(params.getString(NEW_ASSIGNMENT_OPENMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openMin)); String openAMPM = params.getString(NEW_ASSIGNMENT_OPENAMPM); state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, openAMPM); if ((openAMPM.equals("PM")) && (openHour != 12)) { openHour = openHour + 12; } if ((openHour == 12) && (openAMPM.equals("AM"))) { openHour = 0; } Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0); // validate date if (!Validator.checkDate(openDay, openMonth, openYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.opendate") + "."); } // due time int dueMonth = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueMonth)); int dueDay = (new Integer(params.getString(NEW_ASSIGNMENT_DUEDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueDay)); int dueYear = (new Integer(params.getString(NEW_ASSIGNMENT_DUEYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueYear)); int dueHour = (new Integer(params.getString(NEW_ASSIGNMENT_DUEHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(dueHour)); int dueMin = (new Integer(params.getString(NEW_ASSIGNMENT_DUEMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueMin)); String dueAMPM = params.getString(NEW_ASSIGNMENT_DUEAMPM); state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, dueAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); // show alert message when due date is in past. Remove it after user confirms the choice. if (dueTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) == null) { state.setAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE, Boolean.TRUE); } else { // clean the attribute after user confirm state.removeAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE); } if (state.getAttribute(NEW_ASSIGNMENT_PAST_DUE_DATE) != null) { addAlert(state, rb.getString("assig4")); } if (!dueTime.after(openTime)) { addAlert(state, rb.getString("assig3")); } if (!Validator.checkDate(dueDay, dueMonth, dueYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.duedate") + "."); } state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); // close time int closeMonth = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMONTH))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeMonth)); int closeDay = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEDAY))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeDay)); int closeYear = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEYEAR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeYear)); int closeHour = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEHOUR))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(closeHour)); int closeMin = (new Integer(params.getString(NEW_ASSIGNMENT_CLOSEMIN))).intValue(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeMin)); String closeAMPM = params.getString(NEW_ASSIGNMENT_CLOSEAMPM); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, closeAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); // validate date if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + "."); } if (!closeTime.after(openTime)) { addAlert(state, rb.getString("acesubdea3")); } if (closeTime.before(dueTime)) { addAlert(state, rb.getString("acesubdea2")); } // SECTION MOD String sections_string = ""; String mode = (String) state.getAttribute(STATE_MODE); if (mode == null) mode = ""; state.setAttribute(NEW_ASSIGNMENT_SECTION, sections_string); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(params.getString(NEW_ASSIGNMENT_SUBMISSION_TYPE))); int gradeType = -1; // grade type and grade points if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { gradeType = Integer.parseInt(params.getString(NEW_ASSIGNMENT_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(gradeType)); } String r = params.getString(NEW_ASSIGNMENT_USE_REVIEW_SERVICE); String b; // set whether we use the review service or not if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, b); //set whether students can view the review service results r = params.getString(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW); if (r == null) b = Boolean.FALSE.toString(); else b = Boolean.TRUE.toString(); state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, b); // treat the new assignment description as formatted text boolean checkForFormattingErrors = true; // instructor is creating a new assignment - so check for errors String description = processFormattedTextFromBrowser(state, params.getCleanString(NEW_ASSIGNMENT_DESCRIPTION), checkForFormattingErrors); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, description); if (state.getAttribute(CALENDAR) != null) { // calendar enabled for the site if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE).equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); } } else { // no calendar yet for the site state.removeAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } if (params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) != null && params.getString(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE) .equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.TRUE.toString()); } else { state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); } String s = params.getString(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); // set the honor pledge to be "no honor pledge" if (s == null) s = "1"; state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, s); String grading = params.getString(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, grading); // only when choose to associate with assignment in Gradebook String associateAssignment = params.getString(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (grading != null) { if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateAssignment); } else { state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, ""); } if (!grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // gradebook integration only available to point-grade assignment if (gradeType != Assignment.SCORE_GRADE_TYPE) { addAlert(state, rb.getString("addtogradebook.wrongGradeScale")); } // if chosen as "associate", have to choose one assignment from Gradebook if (grading.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE) && StringUtil.trimToNull(associateAssignment) == null) { addAlert(state, rb.getString("grading.associate.alert")); } } } List attachments = (List) state.getAttribute(ATTACHMENTS); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, attachments); if (validify) { if (((description == null) || (description.length() == 0)) && ((attachments == null || attachments.size() == 0))) { // if there is no description nor an attachment, show the following alert message. // One could ignore the message and still post the assignment if (state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) == null) { state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY, Boolean.TRUE.toString()); } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } else { state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); } } if (validify && state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY) != null) { addAlert(state, rb.getString("thiasshas")); } // assignment range? String range = data.getParameters().getString("range"); state.setAttribute(NEW_ASSIGNMENT_RANGE, range); if (range.equals("groups")) { String[] groupChoice = data.getParameters().getStrings("selectedGroups"); if (groupChoice != null && groupChoice.length != 0) { state.setAttribute(NEW_ASSIGNMENT_GROUPS, new ArrayList(Arrays.asList(groupChoice))); } else { state.setAttribute(NEW_ASSIGNMENT_GROUPS, null); addAlert(state, rb.getString("java.alert.youchoosegroup")); } } else { state.removeAttribute(NEW_ASSIGNMENT_GROUPS); } if (state.getAttribute(WITH_GRADES) != null && ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue()) { // the grade point String gradePoints = params.getString(NEW_ASSIGNMENT_GRADE_POINTS); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); if (gradePoints != null) { if (gradeType == 3) { if ((gradePoints.length() == 0)) { // in case of point grade assignment, user must specify maximum grade point addAlert(state, rb.getString("plespethe3")); } else { validPointGrade(state, gradePoints); // when scale is points, grade must be integer and less than maximum value if (state.getAttribute(STATE_MESSAGE) == null) { gradePoints = scalePointGrade(state, gradePoints); } state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, gradePoints); } } } } // allow resubmission numbers String nString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (nString != null) { state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, nString); } // assignment notification option String notiOption = params.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS); if (notiOption != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, notiOption); } } // setNewAssignmentParameters /** * Action is to hide the preview assignment student view */ public void doHide_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); // save user input readGradeForm(data, state, "read"); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_submission_assignment_instruction(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(true)); // save user input readGradeForm(data, state, "read"); } // doShow_submission_assignment_instruction /** * Action is to hide the preview assignment student view */ public void doHide_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true)); } // doHide_preview_assignment_student_view /** * Action is to show the preview assignment student view */ public void doShow_preview_assignment_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(false)); } // doShow_preview_assignment_student_view /** * Action is to hide the preview assignment assignment infos */ public void doHide_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(true)); } // doHide_preview_assignment_assignment /** * Action is to show the preview assignment assignment info */ public void doShow_preview_assignment_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false)); } // doShow_preview_assignment_assignment /** * Action is to hide the assignment option */ public void doHide_assignment_option(RunData data) { setNewAssignmentParameters(data, false); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(true)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, "eventSubmit_doShow_assignment_option"); } // doHide_assignment_option /** * Action is to show the assignment option */ public void doShow_assignment_option(RunData data) { setNewAssignmentParameters(data, false); SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); } // doShow_assignment_option /** * Action is to hide the assignment content in the view assignment page */ public void doHide_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(true)); } // doHide_view_assignment /** * Action is to show the assignment content in the view assignment page */ public void doShow_view_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false)); } // doShow_view_assignment /** * Action is to hide the student view in the view assignment page */ public void doHide_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true)); } // doHide_view_student_view /** * Action is to show the student view in the view assignment page */ public void doShow_view_student_view(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(false)); } // doShow_view_student_view /** * Action is to post assignment */ public void doPost_assignment(RunData data) { // post assignment postOrSaveAssignment(data, "post"); } // doPost_assignment /** * Action is to tag items via an items tagging helper */ public void doHelp_items(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getItemsHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Iterator<String> keys = helperParms.keySet().iterator(); keys .hasNext();) { String key = keys.next(); state.setAttribute(key, helperParms.get(key)); } } // doHelp_items /** * Action is to tag an individual item via an item tagging helper */ public void doHelp_item(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String itemRef = params.getString(ITEM_REF); TaggingHelperInfo helperInfo = provider .getItemHelperInfo(itemRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (Iterator<String> keys = helperParms.keySet().iterator(); keys .hasNext();) { String key = keys.next(); state.setAttribute(key, helperParms.get(key)); } } // doHelp_item /** * Action is to tag an activity via an activity tagging helper */ public void doHelp_activity(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); TaggingProvider provider = taggingManager.findProviderById(params .getString(PROVIDER_ID)); String activityRef = params.getString(ACTIVITY_REF); TaggingHelperInfo helperInfo = provider .getActivityHelperInfo(activityRef); // get into helper mode with this helper tool startHelper(data.getRequest(), helperInfo.getHelperId()); Map<String, ? extends Object> helperParms = helperInfo .getParameterMap(); for (String key : helperParms.keySet()) { state.setAttribute(key, helperParms.get(key)); } } // doHelp_activity /** * post or save assignment */ private void postOrSaveAssignment(RunData data, String postOrSave) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean post = (postOrSave != null) && postOrSave.equals("post"); // assignment old title String aOldTitle = null; // assignment old associated Gradebook entry if any String oAssociateGradebookAssignment = null; String mode = (String) state.getAttribute(STATE_MODE); if (!mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT)) { // read input data if the mode is not preview mode setNewAssignmentParameters(data, true); } String assignmentId = params.getString("assignmentId"); String assignmentContentId = params.getString("assignmentContentId"); // whether this is an editing which changes non-electronic assignment to any other type? boolean bool_change_from_non_electronic = false; if (state.getAttribute(STATE_MESSAGE) == null) { // AssignmentContent object AssignmentContentEdit ac = getAssignmentContentEdit(state, assignmentContentId); // Assignment AssignmentEdit a = getAssignmentEdit(state, assignmentId); bool_change_from_non_electronic = change_from_non_electronic(state, assignmentId, assignmentContentId, ac); // put the names and values into vm file String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE); String order = (String) state.getAttribute(NEW_ASSIGNMENT_ORDER); // open time Time openTime = getOpenTime(state); // due time Time dueTime = getDueTime(state); // close time Time closeTime = dueTime; boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue(); if (enableCloseDate) { closeTime = getCloseTime(state); } // sections String section = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION); int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue(); int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue(); String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION); String checkAddDueTime = state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)!=null?(String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE):null; String checkAutoAnnounce = (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); String addtoGradebook = state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null?(String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK):"" ; String associateGradebookAssignment = (String) state.getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?(String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):null; boolean useReviewService = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE)); boolean allowStudentViewReport = "true".equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW)); // the attachments List attachments = (List) state.getAttribute(ATTACHMENTS); List attachments1 = EntityManager.newReferenceList(attachments); // set group property String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE); Collection groups = new Vector(); try { Site site = SiteService.getSite(siteId); Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS); if (range.equals(Assignment.AssignmentAccess.GROUPED) && (groupChoice == null || groupChoice.size() == 0)) { // show alert if no group is selected for the group access assignment addAlert(state, rb.getString("java.alert.youchoosegroup")); } else if (groupChoice != null) { for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();) { String groupId = (String) iGroups.next(); groups.add(site.getGroup(groupId)); } } } catch (Exception e) { Log.warn("chef", this + e.getMessage()); } if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null)) { aOldTitle = a.getTitle(); // old open time Time oldOpenTime = a.getOpenTime(); // old due time Time oldDueTime = a.getDueTime(); // commit the changes to AssignmentContent object commitAssignmentContentEdit(state, ac, title, submissionType,useReviewService,allowStudentViewReport, gradeType, gradePoints, description, checkAddHonorPledge, attachments1); // set the Assignment Properties object ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit(); oAssociateGradebookAssignment = aPropertiesEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); editAssignmentProperties(a, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit, post); // the notification option if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // comment the changes to Assignment object commitAssignmentEdit(state, post, ac, a, title, openTime, dueTime, closeTime, enableCloseDate, section, range, groups); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); resetAssignment(state); } if (post) { // only if user is posting the assignment if (ac.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // update submissions updateNonElectronicSubmissions(state, a); } else if (bool_change_from_non_electronic) { // not non_electronic type any more List submissions = AssignmentService.getSubmissions(a); if (submissions != null && submissions.size() >0) { // assignment already exist and with submissions for (Iterator iSubmissions = submissions.iterator(); iSubmissions.hasNext();) { AssignmentSubmission s = (AssignmentSubmission) iSubmissions.next(); try { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference()); sEdit.setSubmitted(false); sEdit.setTimeSubmitted(null); AssignmentService.commitEdit(sEdit); } catch (Exception e) { Log.debug("chef", this + e.getMessage() + s.getReference()); } } } } // add the due date to schedule if the schedule exists integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit); // the open date been announced integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, oldOpenTime); // integrate with Gradebook try { initIntegrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range); } catch (AssignmentHasIllegalPointsException e) { addAlert(state, rb.getString("addtogradebook.illegalPoints")); } } //if } // if } // if // set default sorting setDefaultSort(state); } // doPost_assignment /** * */ private boolean change_from_non_electronic(SessionState state, String assignmentId, String assignmentContentId, AssignmentContentEdit ac) { // whether this is an editing which changes non-electronic assignment to any other type? if (StringUtil.trimToNull(assignmentId) != null && StringUtil.trimToNull(assignmentContentId) != null) { // editing if (ac.getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION && ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // changing from non-electronic type return true; } } return false; } /** * default sorting */ private void setDefaultSort(SessionState state) { state.setAttribute(SORTED_BY, SORTED_BY_DEFAULT); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } /** * Add submission objects if necessary for non-electronic type of assignment * @param state * @param a */ private void addRemoveSubmissionsForNonElectronicAssignment(SessionState state, List submissions, HashSet<String> addSubmissionForUsers, HashSet<String> removeSubmissionForUsers, Assignment a) { // create submission object for those user who doesn't have one yet for (Iterator iUserIds = addSubmissionForUsers.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null) { // construct fake submissions for grading purpose AssignmentSubmissionEdit submission = AssignmentService.addSubmission(a.getContext(), a.getId(), userId); submission.setTimeSubmitted(TimeService.newTime()); submission.setSubmitted(true); submission.setAssignment(a); AssignmentService.commitEdit(submission); } } catch (Exception e) { Log.warn("chef", this + e.toString() + "error adding submission for userId = " + userId); } } // remove submission object for those who no longer in the site for (Iterator iUserIds = removeSubmissionForUsers.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); String submissionRef = null; // TODO: we don't have an efficient way to retrieve specific user's submission now, so until then, we still need to iterate the whole submission list for (Iterator iSubmissions=submissions.iterator(); iSubmissions.hasNext() && submissionRef == null;) { AssignmentSubmission submission = (AssignmentSubmission) iSubmissions.next(); List submitterIds = submission.getSubmitterIds(); if (submitterIds != null && submitterIds.size() > 0 && userId.equals((String) submitterIds.get(0))) { submissionRef = submission.getReference(); } } if (submissionRef != null) { try { AssignmentSubmissionEdit submissionEdit = AssignmentService.editSubmission(submissionRef); AssignmentService.removeSubmission(submissionEdit); } catch (Exception e) { Log.warn("chef", this + e.toString() + " error remove submission for userId = " + userId); } } } } private void initIntegrateWithGradebook(SessionState state, String siteId, String aOldTitle, String oAssociateGradebookAssignment, AssignmentEdit a, String title, Time dueTime, int gradeType, String gradePoints, String addtoGradebook, String associateGradebookAssignment, String range) { String context = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean gradebookExists = isGradebookDefined(); // only if the gradebook is defined if (gradebookExists) { GradebookService g = (GradebookService) (org.sakaiproject.service.gradebook.shared.GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); String aReference = a.getReference(); String addUpdateRemoveAssignment = "remove"; if (!addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // if integrate with Gradebook if (!AssignmentService.getAllowGroupAssignmentsInGradebook() && (range.equals("groups"))) { // if grouped assignment is not allowed to add into Gradebook addAlert(state, rb.getString("java.alert.noGroupedAssignmentIntoGB")); String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); aEdit.getPropertiesEdit().removeProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); aEdit.getPropertiesEdit().removeProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null); } else { if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { addUpdateRemoveAssignment = AssignmentService.GRADEBOOK_INTEGRATION_ADD; } else if (addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE)) { addUpdateRemoveAssignment = "update"; } if (!addUpdateRemoveAssignment.equals("remove") && gradeType == 3) { try { integrateGradebook(state, aReference, associateGradebookAssignment, addUpdateRemoveAssignment, aOldTitle, title, Integer.parseInt (gradePoints), dueTime, null, null); // add all existing grades, if any, into Gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update"); // if the assignment has been assoicated with a different entry in gradebook before, remove those grades from the entry in Gradebook if (StringUtil.trimToNull(oAssociateGradebookAssignment) != null && !oAssociateGradebookAssignment.equals(associateGradebookAssignment)) { // if the old assoicated assignment entry in GB is an external one, but doesn't have anything assoicated with it in Assignment tool, remove it removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,g, gradebookUid); } } catch (NumberFormatException nE) { alertInvalidPoint(state, gradePoints); } } else { integrateGradebook(state, aReference, associateGradebookAssignment, "remove", null, null, -1, null, null, null); } } } else { // need to remove the associated gradebook entry if 1) it is external and 2) no other assignment are associated with it removeNonAssociatedExternalGradebookEntry(context, a.getReference(), oAssociateGradebookAssignment,g, gradebookUid); } } } private void removeNonAssociatedExternalGradebookEntry(String context, String assignmentReference, String associateGradebookAssignment, GradebookService g, String gradebookUid) { boolean isExternalAssignmentDefined=g.isExternalAssignmentDefined(gradebookUid, associateGradebookAssignment); if (isExternalAssignmentDefined) { // iterate through all assignments currently in the site, see if any is associated with this GB entry Iterator i = AssignmentService.getAssignmentsForContext(context); boolean found = false; while (!found && i.hasNext()) { Assignment aI = (Assignment) i.next(); String gbEntry = aI.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); if (aI.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED) == null && gbEntry != null && gbEntry.equals(associateGradebookAssignment) && !aI.getReference().equals(assignmentReference)) { found = true; } } // so if none of the assignment in this site is associated with the entry, remove the entry if (!found) { g.removeExternalAssessment(gradebookUid, associateGradebookAssignment); } } } private void integrateWithAnnouncement(SessionState state, String aOldTitle, AssignmentEdit a, String title, Time openTime, String checkAutoAnnounce, Time oldOpenTime) { if (checkAutoAnnounce.equalsIgnoreCase(Boolean.TRUE.toString())) { AnnouncementChannel channel = (AnnouncementChannel) state.getAttribute(ANNOUNCEMENT_CHANNEL); if (channel != null) { // whether the assignment's title or open date has been updated boolean updatedTitle = false; boolean updatedOpenDate = false; String openDateAnnounced = StringUtil.trimToNull(a.getProperties().getProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED)); String openDateAnnouncementId = StringUtil.trimToNull(a.getPropertiesEdit().getProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID)); if (openDateAnnounced != null && openDateAnnouncementId != null) { try { AnnouncementMessage message = channel.getAnnouncementMessage(openDateAnnouncementId); if (!message.getAnnouncementHeader().getSubject().contains(title))/*whether title has been changed*/ { updatedTitle = true; } if (!message.getBody().contains(openTime.toStringLocalFull())) /*whether open date has been changed*/ { updatedOpenDate = true; } } catch (IdUnusedException e) { Log.warn("chef", e.getMessage()); } catch (PermissionException e) { Log.warn("chef", e.getMessage()); } } // need to create announcement message if assignment is added or assignment has been updated if (openDateAnnounced == null || updatedTitle || updatedOpenDate) { try { AnnouncementMessageEdit message = channel.addAnnouncementMessage(); AnnouncementMessageHeaderEdit header = message.getAnnouncementHeaderEdit(); header.setDraft(/* draft */false); header.replaceAttachments(/* attachment */EntityManager.newReferenceList()); if (openDateAnnounced == null) { // making new announcement header.setSubject(/* subject */rb.getString("assig6") + " " + title); } else { // updated title header.setSubject(/* subject */rb.getString("assig5") + " " + title); } if (updatedOpenDate) { // revised assignment open date message.setBody(/* body */rb.getString("newope") + " " + FormattedText.convertPlaintextToFormattedText(title) + " " + rb.getString("is") + " " + openTime.toStringLocalFull() + ". "); } else { // assignment open date message.setBody(/* body */rb.getString("opedat") + " " + FormattedText.convertPlaintextToFormattedText(title) + " " + rb.getString("is") + " " + openTime.toStringLocalFull() + ". "); } // group information if (a.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { try { // get the group ids selected Collection groupRefs = a.getGroups(); // make a collection of Group objects Collection groups = new Vector(); //make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); groups.add(site.getGroup(groupRef)); } // set access header.setGroupAccess(groups); } catch (Exception exception) { // log Log.warn("chef", exception.getMessage()); } } else { // site announcement header.clearGroupAccess(); } channel.commitMessage(message, NotificationService.NOTI_NONE); // commit related properties into Assignment object String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); aEdit.getPropertiesEdit().addProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED, Boolean.TRUE.toString()); if (message != null) { aEdit.getPropertiesEdit().addProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID, message.getId()); } AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotmak")); } } } } // if } private void integrateWithCalendar(SessionState state, AssignmentEdit a, String title, Time dueTime, String checkAddDueTime, Time oldDueTime, ResourcePropertiesEdit aPropertiesEdit) { if (state.getAttribute(CALENDAR) != null) { Calendar c = (Calendar) state.getAttribute(CALENDAR); String dueDateScheduled = a.getProperties().getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); String oldEventId = aPropertiesEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); CalendarEvent e = null; if (dueDateScheduled != null || oldEventId != null) { // find the old event boolean found = false; if (oldEventId != null && c != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { Log.warn("chef", "The old event has been deleted: event id=" + oldEventId + ". "); } catch (PermissionException ee) { Log.warn("chef", "You do not have the permission to view the schedule event id= " + oldEventId + "."); } } else { TimeBreakdown b = oldDueTime.breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); try { Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null) .iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1) { found = true; } } } catch (PermissionException ignore) { // ignore PermissionException } } if (found) { // remove the founded old event try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotrem") + " " + title + ". "); } catch (InUseException ee) { Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen")); } catch (IdUnusedException ee) { Log.warn("chef", rb.getString("cannotfin6") + e.getId()); } } } if (checkAddDueTime.equalsIgnoreCase(Boolean.TRUE.toString())) { if (c != null) { // commit related properties into Assignment object String ref = ""; try { ref = a.getReference(); AssignmentEdit aEdit = AssignmentService.editAssignment(ref); try { e = null; CalendarEvent.EventAccess eAccess = CalendarEvent.EventAccess.SITE; Collection eGroups = new Vector(); if (aEdit.getAccess().equals(Assignment.AssignmentAccess.GROUPED)) { eAccess = CalendarEvent.EventAccess.GROUPED; Collection groupRefs = aEdit.getGroups(); // make a collection of Group objects from the collection of group ref strings Site site = SiteService.getSite((String) state.getAttribute(STATE_CONTEXT_STRING)); for (Iterator iGroupRefs = groupRefs.iterator(); iGroupRefs.hasNext();) { String groupRef = (String) iGroupRefs.next(); eGroups.add(site.getGroup(groupRef)); } } e = c.addEvent(/* TimeRange */TimeService.newTimeRange(dueTime.getTime(), /* 0 duration */0 * 60 * 1000), /* title */rb.getString("due") + " " + title, /* description */rb.getString("assig1") + " " + title + " " + "is due on " + dueTime.toStringLocalFull() + ". ", /* type */rb.getString("deadl"), /* location */"", /* access */ eAccess, /* groups */ eGroups, /* attachments */EntityManager.newReferenceList()); aEdit.getProperties().addProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED, Boolean.TRUE.toString()); if (e != null) { aEdit.getProperties().addProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID, e.getId()); } // edit the calendar ojbject and add an assignment id field CalendarEventEdit edit = c.getEditEvent(e.getId(), org.sakaiproject.calendar.api.CalendarService.EVENT_ADD_CALENDAR); edit.setField(NEW_ASSIGNMENT_DUEDATE_CALENDAR_ASSIGNMENT_ID, a.getId()); c.commitEvent(edit); } catch (IdUnusedException ee) { Log.warn("chef", ee.getMessage()); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotfin1")); } catch (Exception ee) { Log.warn("chef", ee.getMessage()); } // try-catch AssignmentService.commitEdit(aEdit); } catch (Exception ignore) { // ignore the exception Log.warn("chef", rb.getString("cannotfin2") + ref); } } // if } // if } } private void commitAssignmentEdit(SessionState state, boolean post, AssignmentContentEdit ac, AssignmentEdit a, String title, Time openTime, Time dueTime, Time closeTime, boolean enableCloseDate, String s, String range, Collection groups) { a.setTitle(title); a.setContent(ac); a.setContext((String) state.getAttribute(STATE_CONTEXT_STRING)); a.setSection(s); a.setOpenTime(openTime); a.setDueTime(dueTime); // set the drop dead date as the due date a.setDropDeadTime(dueTime); if (enableCloseDate) { a.setCloseTime(closeTime); } else { // if editing an old assignment with close date if (a.getCloseTime() != null) { a.setCloseTime(null); } } // post the assignment a.setDraft(!post); try { if (range.equals("site")) { a.setAccess(Assignment.AssignmentAccess.SITE); a.clearGroupAccess(); } else if (range.equals("groups")) { a.setGroupAccess(groups); } } catch (PermissionException e) { addAlert(state, rb.getString("youarenot1")); } if (state.getAttribute(STATE_MESSAGE) == null) { // commit assignment first AssignmentService.commitEdit(a); } } private void editAssignmentProperties(AssignmentEdit a, String checkAddDueTime, String checkAutoAnnounce, String addtoGradebook, String associateGradebookAssignment, String allowResubmitNumber, ResourcePropertiesEdit aPropertiesEdit, boolean post) { if (aPropertiesEdit.getProperty("newAssignment") != null) { if (aPropertiesEdit.getProperty("newAssignment").equalsIgnoreCase(Boolean.TRUE.toString())) { // not a newly created assignment, been added. aPropertiesEdit.addProperty("newAssignment", Boolean.FALSE.toString()); } } else { // for newly created assignment aPropertiesEdit.addProperty("newAssignment", Boolean.TRUE.toString()); } if (checkAddDueTime != null) { aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, checkAddDueTime); } else { aPropertiesEdit.removeProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE); } aPropertiesEdit.addProperty(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, checkAutoAnnounce); aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, addtoGradebook); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, associateGradebookAssignment); if (post && addtoGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_ADD)) { // if the choice is to add an entry into Gradebook, let just mark it as associated with such new entry then aPropertiesEdit.addProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_ASSOCIATE); aPropertiesEdit.addProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, a.getReference()); } // allow resubmit number if (allowResubmitNumber != null) { aPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } } private void commitAssignmentContentEdit(SessionState state, AssignmentContentEdit ac, String title, int submissionType,boolean useReviewService, boolean allowStudentViewReport, int gradeType, String gradePoints, String description, String checkAddHonorPledge, List attachments1) { ac.setTitle(title); ac.setInstructions(description); ac.setHonorPledge(Integer.parseInt(checkAddHonorPledge)); ac.setTypeOfSubmission(submissionType); ac.setAllowReviewService(useReviewService); ac.setAllowStudentViewReport(allowStudentViewReport); ac.setTypeOfGrade(gradeType); if (gradeType == 3) { try { ac.setMaxGradePoint(Integer.parseInt(gradePoints)); } catch (NumberFormatException e) { alertInvalidPoint(state, gradePoints); } } ac.setGroupProject(true); ac.setIndividuallyGraded(false); if (submissionType != 1) { ac.setAllowAttachments(true); } else { ac.setAllowAttachments(false); } // clear attachments ac.clearAttachments(); // add each attachment Iterator it = EntityManager.newReferenceList(attachments1).iterator(); while (it.hasNext()) { Reference r = (Reference) it.next(); ac.addAttachment(r); } state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false)); // commit the changes AssignmentService.commitEdit(ac); } /** * reorderAssignments */ private void reorderAssignments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List assignments = prepPage(state); Iterator it = assignments.iterator(); // temporarily allow the user to read and write from assignments (asn.revise permission) SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); while (it.hasNext()) // reads and writes the parameter for default ordering { Assignment a = (Assignment) it.next(); String assignmentid = a.getId(); String assignmentposition = params.getString("position_" + assignmentid); AssignmentEdit ae = getAssignmentEdit(state, assignmentid); ae.setPosition_order(new Long(assignmentposition).intValue()); AssignmentService.commitEdit(ae); } // clear the permission SecurityService.clearAdvisors(); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); //resetAssignment(state); } } // reorderAssignments private AssignmentEdit getAssignmentEdit(SessionState state, String assignmentId) { AssignmentEdit a = null; if (assignmentId.length() == 0) { // create a new assignment try { a = AssignmentService.addAssignment((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot1")); } } else { try { // edit assignment a = AssignmentService.editAssignment(assignmentId); } catch (InUseException e) { addAlert(state, rb.getString("theassicon")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } // try-catch } // if-else return a; } private AssignmentContentEdit getAssignmentContentEdit(SessionState state, String assignmentContentId) { AssignmentContentEdit ac = null; if (assignmentContentId.length() == 0) { // new assignment try { ac = AssignmentService.addAssignmentContent((String) state.getAttribute(STATE_CONTEXT_STRING)); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot3")); } } else { try { // edit assignment ac = AssignmentService.editAssignmentContent(assignmentContentId); } catch (InUseException e) { addAlert(state, rb.getString("theassicon")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin4")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot15")); } } return ac; } private Time getOpenTime(SessionState state) { int openMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMONTH)).intValue(); int openDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENDAY)).intValue(); int openYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENYEAR)).intValue(); int openHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENHOUR)).intValue(); int openMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_OPENMIN)).intValue(); String openAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_OPENAMPM); if ((openAMPM.equals("PM")) && (openHour != 12)) { openHour = openHour + 12; } if ((openHour == 12) && (openAMPM.equals("AM"))) { openHour = 0; } Time openTime = TimeService.newTimeLocal(openYear, openMonth, openDay, openHour, openMin, 0, 0); return openTime; } private Time getCloseTime(SessionState state) { Time closeTime; int closeMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); return closeTime; } private Time getDueTime(SessionState state) { int dueMonth = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)).intValue(); int dueDay = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEDAY)).intValue(); int dueYear = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)).intValue(); int dueHour = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)).intValue(); int dueMin = ((Integer) state.getAttribute(NEW_ASSIGNMENT_DUEMIN)).intValue(); String dueAMPM = (String) state.getAttribute(NEW_ASSIGNMENT_DUEAMPM); if ((dueAMPM.equals("PM")) && (dueHour != 12)) { dueHour = dueHour + 12; } if ((dueHour == 12) && (dueAMPM.equals("AM"))) { dueHour = 0; } Time dueTime = TimeService.newTimeLocal(dueYear, dueMonth, dueDay, dueHour, dueMin, 0, 0); return dueTime; } private Time getAllowSubmitCloseTime(SessionState state) { int closeMonth = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMONTH)).intValue(); int closeDay = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEDAY)).intValue(); int closeYear = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEYEAR)).intValue(); int closeHour = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEHOUR)).intValue(); int closeMin = ((Integer) state.getAttribute(ALLOW_RESUBMIT_CLOSEMIN)).intValue(); String closeAMPM = (String) state.getAttribute(ALLOW_RESUBMIT_CLOSEAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); return closeTime; } /** * Action is to post new assignment */ public void doSave_assignment(RunData data) { postOrSaveAssignment(data, "save"); } // doSave_assignment /** * Action is to reorder assignments */ public void doReorder_assignment(RunData data) { reorderAssignments(data); } // doReorder_assignments /** * Action is to preview the selected assignment */ public void doPreview_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); setNewAssignmentParameters(data, false); String assignmentId = data.getParameters().getString("assignmentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_ID, assignmentId); String assignmentContentId = data.getParameters().getString("assignmentContentId"); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENTCONTENT_ID, assignmentContentId); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, new Boolean(false)); state.setAttribute(PREVIEW_ASSIGNMENT_STUDENT_VIEW_HIDE_FLAG, new Boolean(true)); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT); } } // doPreview_assignment /** * Action is to view the selected assignment */ public void doView_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // show the assignment portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_ASSIGNMENT_FLAG, new Boolean(false)); // show the student view portion state.setAttribute(VIEW_ASSIGNMENT_HIDE_STUDENT_VIEW_FLAG, new Boolean(true)); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_ASSIGNMENT); } } // doView_Assignment /** * Action is for student to view one assignment content */ public void doView_assignment_as_student(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = params.getString("assignmentId"); state.setAttribute(VIEW_ASSIGNMENT_ID, assignmentId); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_ASSIGNMENT); } } // doView_assignment_as_student /** * Action is to show the edit assignment screen */ public void doEdit_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String assignmentId = StringUtil.trimToNull(params.getString("assignmentId")); // whether the user can modify the assignment state.setAttribute(EDIT_ASSIGNMENT_ID, assignmentId); try { Assignment a = AssignmentService.getAssignment(assignmentId); // for the non_electronice assignment, submissions are auto-generated by the time that assignment is created; // don't need to go through the following checkings. if (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { Iterator submissions = AssignmentService.getSubmissions(a).iterator(); if (submissions.hasNext()) { // any submitted? boolean anySubmitted = false; for (;submissions.hasNext() && !anySubmitted;) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getSubmitted() && s.getTimeSubmitted() != null) { anySubmitted = true; } } // any draft submission boolean anyDraft = false; for (;submissions.hasNext() && !anyDraft;) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (!s.getSubmitted()) { anyDraft = true; } } if (anySubmitted) { // if there is any submitted submission to this assignment, show alert addAlert(state, rb.getString("assig1") + " " + a.getTitle() + " " + rb.getString("hassum")); } if (anyDraft) { // otherwise, show alert about someone has started working on the assignment, not necessarily submitted addAlert(state, rb.getString("hasDraftSum")); } } } // SECTION MOD state.setAttribute(STATE_SECTION_STRING, a.getSection()); // put the names and values into vm file state.setAttribute(NEW_ASSIGNMENT_TITLE, a.getTitle()); state.setAttribute(NEW_ASSIGNMENT_ORDER, a.getPosition_order()); TimeBreakdown openTime = a.getOpenTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(openTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(openTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(openTime.getYear())); int openHour = openTime.getHour(); if (openHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "AM"); } if (openHour == 0) { // for midnight point, we mark it as 12AM openHour = 12; } state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer((openHour > 12) ? openHour - 12 : openHour)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(openTime.getMin())); TimeBreakdown dueTime = a.getDueTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(dueTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(dueTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(dueTime.getYear())); int dueHour = dueTime.getHour(); if (dueHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "AM"); } if (dueHour == 0) { // for midnight point, we mark it as 12AM dueHour = 12; } state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer((dueHour > 12) ? dueHour - 12 : dueHour)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(dueTime.getMin())); // generate alert when editing an assignment past due date if (a.getDueTime().before(TimeService.newTime())) { addAlert(state, rb.getString("youarenot17")); } if (a.getCloseTime() != null) { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); TimeBreakdown closeTime = a.getCloseTime().breakdownLocal(); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(closeTime.getMonth())); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(closeTime.getDay())); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(closeTime.getYear())); int closeHour = closeTime.getHour(); if (closeHour >= 12) { state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM"); } else { state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "AM"); } if (closeHour == 0) { // for the midnight point, we mark it as 12 AM closeHour = 12; } state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer((closeHour > 12) ? closeHour - 12 : closeHour)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(closeTime.getMin())); } else { state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, state.getAttribute(NEW_ASSIGNMENT_DUEMONTH)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, state.getAttribute(NEW_ASSIGNMENT_DUEDAY)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, state.getAttribute(NEW_ASSIGNMENT_DUEYEAR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, state.getAttribute(NEW_ASSIGNMENT_DUEHOUR)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, state.getAttribute(NEW_ASSIGNMENT_DUEMIN)); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, state.getAttribute(NEW_ASSIGNMENT_DUEAMPM)); } state.setAttribute(NEW_ASSIGNMENT_SECTION, a.getSection()); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(a.getContent().getTypeOfSubmission())); int typeOfGrade = a.getContent().getTypeOfGrade(); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(typeOfGrade)); if (typeOfGrade == 3) { state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, a.getContent().getMaxGradePointDisplay()); } state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, a.getContent().getInstructions()); ResourceProperties properties = a.getProperties(); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE)); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, properties.getProperty( ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE)); state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, Integer.toString(a.getContent().getHonorPledge())); state.setAttribute(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, properties.getProperty(AssignmentService.NEW_ASSIGNMENT_ADD_TO_GRADEBOOK)); state.setAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT, properties.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); state.setAttribute(ATTACHMENTS, a.getContent().getAttachments()); // notification option if (properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { state.setAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, properties.getProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // group setting if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { state.setAttribute(NEW_ASSIGNMENT_RANGE, "site"); } else { state.setAttribute(NEW_ASSIGNMENT_RANGE, "groups"); } state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null?properties.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER):"0"); // set whether we use the review service or not state.setAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE, new Boolean(a.getContent().getAllowReviewService()).toString()); //set whether students can view the review service results state.setAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW, new Boolean(a.getContent().getAllowStudentViewReport()).toString()); state.setAttribute(NEW_ASSIGNMENT_GROUPS, a.getGroups()); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT); } // doEdit_Assignment /** * Action is to show the delete assigment confirmation screen */ public void doDelete_confirm_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String[] assignmentIds = params.getStrings("selectedAssignments"); if (assignmentIds != null) { Vector ids = new Vector(); for (int i = 0; i < assignmentIds.length; i++) { String id = (String) assignmentIds[i]; if (!AssignmentService.allowRemoveAssignment(id)) { addAlert(state, rb.getString("youarenot9") + " " + id + ". "); } ids.add(id); } if (state.getAttribute(STATE_MESSAGE) == null) { // can remove all the selected assignments state.setAttribute(DELETE_ASSIGNMENT_IDS, ids); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_DELETE_ASSIGNMENT); } } else { addAlert(state, rb.getString("youmust6")); } } // doDelete_confirm_Assignment /** * Action is to delete the confirmed assignments */ public void doDelete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String assignmentId = (String) ids.get(i); try { AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); ResourcePropertiesEdit pEdit = aEdit.getPropertiesEdit(); String associateGradebookAssignment = pEdit.getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String title = aEdit.getTitle(); // remove releted event if there is one String isThereEvent = pEdit.getProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); if (isThereEvent != null && isThereEvent.equals(Boolean.TRUE.toString())) { removeCalendarEvent(state, aEdit, pEdit, title); } // if-else if (aEdit.getContent().getTypeOfSubmission() == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // if this is non-electronic submission, remove all the submissions List submissions = AssignmentService.getSubmissions(aEdit); if (submissions != null) { for (Iterator sIterator=submissions.iterator(); sIterator.hasNext();) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); try { AssignmentService.removeSubmission(AssignmentService.editSubmission((s.getReference()))); } catch (Exception eee) { addAlert(state, rb.getString("youarenot11_s") + " " + s.getReference() + ". "); } } } try { // remove the assignment content AssignmentService.removeAssignmentContent(AssignmentService.editAssignmentContent(aEdit.getContent().getReference())); } catch (Exception eee) { addAlert(state, rb.getString("youarenot11_c") + " " + aEdit.getContentReference() + ". "); } try { // remove the assignment afterwards AssignmentService.removeAssignment(aEdit); } catch (Exception ee) { addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". "); } } else { // for assignment with other type of submission if (!AssignmentService.getSubmissions(aEdit).iterator().hasNext()) { // there is no submission to this assignment yet, delete the assignment and assignment content record completely try { // remove the assignment content AssignmentService.removeAssignmentContent(AssignmentService.editAssignmentContent(aEdit.getContent().getReference())); } catch (Exception ee) { addAlert(state, rb.getString("youarenot11_c") + " " + aEdit.getContentReference() + ". "); } try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(aEdit)); } } AssignmentService.removeAssignment(aEdit); } catch (PermissionException ee) { addAlert(state, rb.getString("youarenot11") + " " + aEdit.getTitle() + ". "); } } else { // remove the assignment by marking the remove status property true pEdit.addProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED, Boolean.TRUE.toString()); AssignmentService.commitEdit(aEdit); } } // remove from Gradebook integrateGradebook(state, (String) ids.get (i), associateGradebookAssignment, "remove", null, null, -1, null, null, null); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2")); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot6")); } } // for if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); // reset paging information after the assignment been deleted resetPaging(state); } } // doDelete_Assignment private void removeCalendarEvent(SessionState state, AssignmentEdit aEdit, ResourcePropertiesEdit pEdit, String title) throws PermissionException { // remove the associated calender event Calendar c = (Calendar) state.getAttribute(CALENDAR); if (c != null) { // already has calendar object // get the old event CalendarEvent e = null; boolean found = false; String oldEventId = pEdit.getProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); if (oldEventId != null) { try { e = c.getEvent(oldEventId); found = true; } catch (IdUnusedException ee) { // no action needed for this condition } catch (PermissionException ee) { } } else { TimeBreakdown b = aEdit.getDueTime().breakdownLocal(); // TODO: check- this was new Time(year...), not local! -ggolden Time startTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 0, 0, 0, 0); Time endTime = TimeService.newTimeLocal(b.getYear(), b.getMonth(), b.getDay(), 23, 59, 59, 999); Iterator events = c.getEvents(TimeService.newTimeRange(startTime, endTime), null).iterator(); while ((!found) && (events.hasNext())) { e = (CalendarEvent) events.next(); if (((String) e.getDisplayName()).indexOf(rb.getString("assig1") + " " + title) != -1) { found = true; } } } // remove the founded old event if (found) { // found the old event delete it try { c.removeEvent(c.getEditEvent(e.getId(), CalendarService.EVENT_REMOVE_CALENDAR)); pEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); pEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); } catch (PermissionException ee) { Log.warn("chef", rb.getString("cannotrem") + " " + title + ". "); } catch (InUseException ee) { Log.warn("chef", rb.getString("somelsis") + " " + rb.getString("calen")); } catch (IdUnusedException ee) { Log.warn("chef", rb.getString("cannotfin6") + e.getId()); } } } } /** * Action is to delete the assignment and also the related AssignmentSubmission */ public void doDeep_delete_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the delete assignment ids Vector ids = (Vector) state.getAttribute(DELETE_ASSIGNMENT_IDS); for (int i = 0; i < ids.size(); i++) { String currentId = (String) ids.get(i); try { AssignmentEdit a = AssignmentService.editAssignment(currentId); try { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); if (taggingManager.isTaggable()) { for (TaggingProvider provider : taggingManager .getProviders()) { provider.removeTags(assignmentActivityProducer .getActivity(a)); } } AssignmentService.removeAssignment(a); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot11") + " " + a.getTitle() + ". "); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("assig2")); } } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(DELETE_ASSIGNMENT_IDS, new Vector()); state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } } // doDeep_delete_Assignment /** * Action is to show the duplicate assignment screen */ public void doDuplicate_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the view, so start with first page again. resetPaging(state); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); ParameterParser params = data.getParameters(); String assignmentId = StringUtil.trimToNull(params.getString("assignmentId")); if (assignmentId != null) { try { AssignmentEdit aEdit = AssignmentService.addDuplicateAssignment(contextString, assignmentId); // clean the duplicate's property ResourcePropertiesEdit aPropertiesEdit = aEdit.getPropertiesEdit(); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_DUE_DATE_SCHEDULED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_DUEDATE_CALENDAR_EVENT_ID); aPropertiesEdit.removeProperty(NEW_ASSIGNMENT_OPEN_DATE_ANNOUNCED); aPropertiesEdit.removeProperty(ResourceProperties.PROP_ASSIGNMENT_OPENDATE_ANNOUNCEMENT_MESSAGE_ID); AssignmentService.commitEdit(aEdit); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot5")); } catch (IdInvalidException e) { addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("isnotval")); } catch (IdUnusedException e) { addAlert(state, rb.getString("theassiid") + " " + assignmentId + " " + rb.getString("hasnotbee")); } catch (Exception e) { } } } // doDuplicate_Assignment /** * Action is to show the grade submission screen */ public void doGrade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // reset the submission context resetViewSubmission(state); ParameterParser params = data.getParameters(); // reset the grade assignment id state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID, params.getString("assignmentId")); state.setAttribute(GRADE_SUBMISSION_SUBMISSION_ID, params.getString("submissionId")); // allow resubmit number String allowResubmitNumber = "0"; Assignment a = null; try { a = AssignmentService.getAssignment((String) state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_ID)); if (a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { allowResubmitNumber= a.getProperties().getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } try { AssignmentSubmission s = AssignmentService.getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID)); if ((s.getFeedbackText() == null) || (s.getFeedbackText().length() == 0)) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getSubmittedText()); } else { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, s.getFeedbackText()); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, s.getFeedbackComment()); List v = EntityManager.newReferenceList(); Iterator attachments = s.getFeedbackAttachments().iterator(); while (attachments.hasNext()) { v.add(attachments.next()); } state.setAttribute(ATTACHMENTS, v); state.setAttribute(GRADE_SUBMISSION_GRADE, s.getGrade()); ResourceProperties p = s.getProperties(); if (p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { allowResubmitNumber = p.getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } else if (p.getProperty(GRADE_SUBMISSION_ALLOW_RESUBMIT) != null) { // if there is any legacy setting for generally allow resubmit, set the allow resubmit number to be 1, and remove the legacy property allowResubmitNumber = "1"; } state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, allowResubmitNumber); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_SUBMISSION); } } // doGrade_submission /** * Action is to release all the grades of the submission */ public void doRelease_grades(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); try { // get the assignment Assignment a = AssignmentService.getAssignment(params.getString("assignmentId")); String aReference = a.getReference(); Iterator submissions = AssignmentService.getSubmissions(a).iterator(); while (submissions.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); if (s.getGraded()) { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference()); String grade = s.getGrade(); boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)) .booleanValue() : false; if (withGrade) { // for the assignment tool with grade option, a valide grade is needed if (grade != null && !grade.equals("")) { sEdit.setGradeReleased(true); } } else { // for the assignment tool without grade option, no grade is needed sEdit.setGradeReleased(true); } // also set the return status sEdit.setReturned(true); sEdit.setTimeReturned(TimeService.newTime()); sEdit.setHonorPledgeFlag(Boolean.FALSE.booleanValue()); AssignmentService.commitEdit(sEdit); } } // while // add grades into Gradebook String integrateWithGradebook = a.getProperties().getProperty(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK); if (integrateWithGradebook != null && !integrateWithGradebook.equals(AssignmentService.GRADEBOOK_INTEGRATION_NO)) { // integrate with Gradebook String associateGradebookAssignment = StringUtil.trimToNull(a.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, null, "update"); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } catch (InUseException e) { addAlert(state, rb.getString("somelsis") + " " + rb.getString("submiss")); } } // doRelease_grades /** * Action is to show the assignment in grading page */ public void doExpand_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(true)); } // doExpand_grade_assignment /** * Action is to hide the assignment in grading page */ public void doCollapse_grade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); } // doCollapse_grade_assignment /** * Action is to show the submissions in grading page */ public void doExpand_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true)); } // doExpand_grade_submission /** * Action is to hide the submissions in grading page */ public void doCollapse_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(false)); } // doCollapse_grade_submission /** * Action is to show the grade assignment */ public void doGrade_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // clean state attribute state.removeAttribute(USER_SUBMISSIONS); state.setAttribute(EXPORT_ASSIGNMENT_REF, params.getString("assignmentId")); try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); state.setAttribute(EXPORT_ASSIGNMENT_ID, a.getId()); state.setAttribute(GRADE_ASSIGNMENT_EXPAND_FLAG, new Boolean(false)); state.setAttribute(GRADE_SUBMISSION_EXPAND_FLAG, new Boolean(true)); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); // we are changing the view, so start with first page again. resetPaging(state); } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } // doGrade_assignment /** * Action is to show the View Students assignment screen */ public void doView_students_assignment(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT); } // doView_students_Assignment /** * Action is to show the student submissions */ public void doShow_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // add the student id into the table t.add(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doShow_student_submission /** * Action is to hide the student submissions */ public void doHide_student_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Set t = (Set) state.getAttribute(STUDENT_LIST_SHOW_TABLE); ParameterParser params = data.getParameters(); String id = params.getString("studentId"); // remove the student id from the table t.remove(id); state.setAttribute(STUDENT_LIST_SHOW_TABLE, t); } // doHide_student_submission /** * Action is to show the graded assignment submission */ public void doView_grade(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(VIEW_GRADE_SUBMISSION_ID, params.getString("submissionId")); state.setAttribute(STATE_MODE, MODE_STUDENT_VIEW_GRADE); } // doView_grade /** * Action is to show the student submissions */ public void doReport_submissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_REPORT_SUBMISSIONS); state.setAttribute(SORTED_BY, SORTED_SUBMISSION_BY_LASTNAME); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // doReport_submissions /** * * */ public void doAssignment_form(RunData data) { ParameterParser params = data.getParameters(); String option = (String) params.getString("option"); if (option != null) { if (option.equals("post")) { // post assignment doPost_assignment(data); } else if (option.equals("save")) { // save assignment doSave_assignment(data); } else if (option.equals("reorder")) { // reorder assignments doReorder_assignment(data); } else if (option.equals("preview")) { // preview assignment doPreview_assignment(data); } else if (option.equals("cancel")) { // cancel creating assignment doCancel_new_assignment(data); } else if (option.equals("canceledit")) { // cancel editing assignment doCancel_edit_assignment(data); } else if (option.equals("attach")) { // attachments doAttachments(data); } else if (option.equals("view")) { // view doView(data); } else if (option.equals("permissions")) { // permissions doPermissions(data); } else if (option.equals("returngrade")) { // return grading doReturn_grade_submission(data); } else if (option.equals("savegrade")) { // save grading doSave_grade_submission(data); } else if (option.equals("previewgrade")) { // preview grading doPreview_grade_submission(data); } else if (option.equals("cancelgrade")) { // cancel grading doCancel_grade_submission(data); } else if (option.equals("cancelreorder")) { // cancel reordering doCancel_reorder(data); } else if (option.equals("sortbygrouptitle")) { // read input data setNewAssignmentParameters(data, true); // sort by group title doSortbygrouptitle(data); } else if (option.equals("sortbygroupdescription")) { // read input data setNewAssignmentParameters(data, true); // sort group by description doSortbygroupdescription(data); } else if (option.equals("hide_instruction")) { // hide the assignment instruction doHide_submission_assignment_instruction(data); } else if (option.equals("show_instruction")) { // show the assignment instruction doShow_submission_assignment_instruction(data); } else if (option.equals("sortbygroupdescription")) { // show the assignment instruction doShow_submission_assignment_instruction(data); } else if (option.equals("revise") || option.equals("done")) { // back from the preview mode doDone_preview_new_assignment(data); } } } /** * Action is to use when doAattchmentsadding requested, corresponding to chef_Assignments-new "eventSubmit_doAattchmentsadding" when "add attachments" is clicked */ public void doAttachments(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String mode = (String) state.getAttribute(STATE_MODE); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { setNewAssignmentParameters(data, false); } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { readGradeForm(data, state, "read"); } if (state.getAttribute(STATE_MESSAGE) == null) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.filepicker"); state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatttoassig")); state.setAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT, rb.getString("gen.addatttoassiginstr")); // use the real attachment list state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, state.getAttribute(ATTACHMENTS)); } } /** * readGradeForm */ public void readGradeForm(RunData data, SessionState state, String gradeOption) { ParameterParser params = data.getParameters(); int typeOfGrade = -1; boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue() : false; boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT), checkForFormattingErrors); if (feedbackComment != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment); } String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT)); if (feedbackText != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText); } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS)); String g = params.getCleanString(GRADE_SUBMISSION_GRADE); if (g != null) { state.setAttribute(GRADE_SUBMISSION_GRADE, g); } String sId = (String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID); try { // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); Assignment a = AssignmentService.getSubmission(sId).getAssignment(); typeOfGrade = a.getContent().getTypeOfGrade(); if (withGrade) { // do grade validation only for Assignment with Grade tool if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { if ((grade.length() == 0)) { state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } else { // the preview grade process might already scaled up the grade by 10 if (!((String) state.getAttribute(STATE_MODE)).equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } } // if ungraded and grade type is not "ungraded" type if ((grade == null || grade.equals("ungraded")) && (typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) && gradeOption.equals("release")) { addAlert(state, rb.getString("plespethe2")); } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin5")); } catch (PermissionException e) { addAlert(state, rb.getString("not_allowed_to_view")); } // allow resubmit number and due time if (params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { String allowResubmitNumberString = params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); if (Integer.parseInt(allowResubmitNumberString) != 0) { int closeMonth = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMONTH))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMONTH, new Integer(closeMonth)); int closeDay = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEDAY))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEDAY, new Integer(closeDay)); int closeYear = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEYEAR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEYEAR, new Integer(closeYear)); int closeHour = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEHOUR))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEHOUR, new Integer(closeHour)); int closeMin = (new Integer(params.getString(ALLOW_RESUBMIT_CLOSEMIN))).intValue(); state.setAttribute(ALLOW_RESUBMIT_CLOSEMIN, new Integer(closeMin)); String closeAMPM = params.getString(ALLOW_RESUBMIT_CLOSEAMPM); state.setAttribute(ALLOW_RESUBMIT_CLOSEAMPM, closeAMPM); if ((closeAMPM.equals("PM")) && (closeHour != 12)) { closeHour = closeHour + 12; } if ((closeHour == 12) && (closeAMPM.equals("AM"))) { closeHour = 0; } Time closeTime = TimeService.newTimeLocal(closeYear, closeMonth, closeDay, closeHour, closeMin, 0, 0); state.setAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, String.valueOf(closeTime.getTime())); // validate date if (closeTime.before(TimeService.newTime()) && state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) == null) { state.setAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE, Boolean.TRUE); } else { // clean the attribute after user confirm state.removeAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE); } if (state.getAttribute(NEW_ASSIGNMENT_PAST_CLOSE_DATE) != null) { addAlert(state, rb.getString("acesubdea4")); } if (!Validator.checkDate(closeDay, closeMonth, closeYear)) { addAlert(state, rb.getString("date.invalid") + rb.getString("date.closedate") + "."); } } else { // reset the state attributes state.removeAttribute(ALLOW_RESUBMIT_CLOSEMONTH); state.removeAttribute(ALLOW_RESUBMIT_CLOSEDAY); state.removeAttribute(ALLOW_RESUBMIT_CLOSEYEAR); state.removeAttribute(ALLOW_RESUBMIT_CLOSEHOUR); state.removeAttribute(ALLOW_RESUBMIT_CLOSEMIN); state.removeAttribute(ALLOW_RESUBMIT_CLOSEAMPM); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } } if (state.getAttribute(STATE_MESSAGE) == null) { String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); grade = (typeOfGrade == Assignment.SCORE_GRADE_TYPE)?scalePointGrade(state, grade):grade; state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } /** * Populate the state object, if needed - override to do something! */ protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData data) { super.initState(state, portlet, data); if (m_contentHostingService == null) { m_contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); } String siteId = ToolManager.getCurrentPlacement().getContext(); // show the list of assignment view first if (state.getAttribute(STATE_SELECTED_VIEW) == null) { state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_USER) == null) { state.setAttribute(STATE_USER, UserDirectoryService.getCurrentUser()); } /** The content type image lookup service in the State. */ ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); if (iService == null) { iService = org.sakaiproject.content.cover.ContentTypeImageService.getInstance(); state.setAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE, iService); } // if /** The calendar tool */ if (state.getAttribute(CALENDAR_TOOL_EXIST) == null) { if (!siteHasTool(siteId, "sakai.schedule")) { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.FALSE); state.removeAttribute(CALENDAR); } else { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE); if (state.getAttribute(CALENDAR) == null ) { state.setAttribute(CALENDAR_TOOL_EXIST, Boolean.TRUE); CalendarService cService = org.sakaiproject.calendar.cover.CalendarService.getInstance(); state.setAttribute(STATE_CALENDAR_SERVICE, cService); String calendarId = ServerConfigurationService.getString("calendar", null); if (calendarId == null) { calendarId = cService.calendarReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(CALENDAR, cService.getCalendar(calendarId)); } catch (IdUnusedException e) { Log.info("chef", "No calendar found for site " + siteId); state.removeAttribute(CALENDAR); } catch (PermissionException e) { Log.info("chef", "No permission to get the calender. "); state.removeAttribute(CALENDAR); } catch (Exception ex) { Log.info("chef", "Assignment : Action : init state : calendar exception : " + ex); state.removeAttribute(CALENDAR); } } } } } /** The Announcement tool */ if (state.getAttribute(ANNOUNCEMENT_TOOL_EXIST) == null) { if (!siteHasTool(siteId, "sakai.announcements")) { state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.FALSE); state.removeAttribute(ANNOUNCEMENT_CHANNEL); } else { state.setAttribute(ANNOUNCEMENT_TOOL_EXIST, Boolean.TRUE); if (state.getAttribute(ANNOUNCEMENT_CHANNEL) == null ) { /** The announcement service in the State. */ AnnouncementService aService = (AnnouncementService) state.getAttribute(STATE_ANNOUNCEMENT_SERVICE); if (aService == null) { aService = org.sakaiproject.announcement.cover.AnnouncementService.getInstance(); state.setAttribute(STATE_ANNOUNCEMENT_SERVICE, aService); String channelId = ServerConfigurationService.getString("channel", null); if (channelId == null) { channelId = aService.channelReference(siteId, SiteService.MAIN_CONTAINER); try { state.setAttribute(ANNOUNCEMENT_CHANNEL, aService.getAnnouncementChannel(channelId)); } catch (IdUnusedException e) { Log.warn("chef", "No announcement channel found. "); state.removeAttribute(ANNOUNCEMENT_CHANNEL); } catch (PermissionException e) { Log.warn("chef", "No permission to annoucement channel. "); } catch (Exception ex) { Log.warn("chef", "Assignment : Action : init state : calendar exception : " + ex); } } } } } } // if if (state.getAttribute(STATE_CONTEXT_STRING) == null) { state.setAttribute(STATE_CONTEXT_STRING, siteId); } // if context string is null if (state.getAttribute(SORTED_BY) == null) { setDefaultSort(state); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_BY) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, SORTED_GRADE_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_GRADE_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(SORTED_SUBMISSION_BY) == null) { state.setAttribute(SORTED_SUBMISSION_BY, SORTED_SUBMISSION_BY_LASTNAME); } if (state.getAttribute(SORTED_SUBMISSION_ASC) == null) { state.setAttribute(SORTED_SUBMISSION_ASC, Boolean.TRUE.toString()); } if (state.getAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG) == null) { resetAssignment(state); } if (state.getAttribute(STUDENT_LIST_SHOW_TABLE) == null) { state.setAttribute(STUDENT_LIST_SHOW_TABLE, new HashSet()); } if (state.getAttribute(ATTACHMENTS_MODIFIED) == null) { state.setAttribute(ATTACHMENTS_MODIFIED, new Boolean(false)); } // SECTION MOD if (state.getAttribute(STATE_SECTION_STRING) == null) { state.setAttribute(STATE_SECTION_STRING, "001"); } // // setup the observer to notify the Main panel // if (state.getAttribute(STATE_OBSERVER) == null) // { // // the delivery location for this tool // String deliveryId = clientWindowId(state, portlet.getID()); // // // the html element to update on delivery // String elementId = mainPanelUpdateId(portlet.getID()); // // // the event resource reference pattern to watch for // String pattern = AssignmentService.assignmentReference((String) state.getAttribute (STATE_CONTEXT_STRING), ""); // // state.setAttribute(STATE_OBSERVER, new MultipleEventsObservingCourier(deliveryId, elementId, pattern)); // } if (state.getAttribute(STATE_MODE) == null) { state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); } if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) { state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0)); } if (state.getAttribute(WITH_GRADES) == null) { PortletConfig config = portlet.getPortletConfig(); String withGrades = StringUtil.trimToNull(config.getInitParameter("withGrades")); if (withGrades == null) { withGrades = Boolean.FALSE.toString(); } state.setAttribute(WITH_GRADES, new Boolean(withGrades)); } // whether the choice of emails instructor submission notification is available in the installation if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS) == null) { state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, Boolean.valueOf(ServerConfigurationService.getBoolean(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS, true))); } // whether or how the instructor receive submission notification emails, none(default)|each|digest if (state.getAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT) == null) { state.setAttribute(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, ServerConfigurationService.getString(ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DEFAULT, Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE)); } if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM) == null) { state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_FROM, new Integer(2002)); } if (state.getAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO) == null) { state.setAttribute(NEW_ASSIGNMENT_YEAR_RANGE_TO, new Integer(2012)); } } // initState /** * whether the site has the specified tool * @param siteId * @return */ private boolean siteHasTool(String siteId, String toolId) { boolean rv = false; try { Site s = SiteService.getSite(siteId); if (s.getToolForCommonId(toolId) != null) { rv = true; } } catch (Exception e) { Log.info("chef", this + e.getMessage() + siteId); } return rv; } /** * reset the attributes for view submission */ private void resetViewSubmission(SessionState state) { state.removeAttribute(VIEW_SUBMISSION_ASSIGNMENT_REFERENCE); state.removeAttribute(VIEW_SUBMISSION_TEXT); state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "false"); state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } // resetViewSubmission /** * reset the attributes for view submission */ private void resetAssignment(SessionState state) { // put the input value into the state attributes state.setAttribute(NEW_ASSIGNMENT_TITLE, ""); // get current time Time t = TimeService.newTime(); TimeBreakdown tB = t.breakdownLocal(); int month = tB.getMonth(); int day = tB.getDay(); int year = tB.getYear(); // set the open time to be 12:00 PM state.setAttribute(NEW_ASSIGNMENT_OPENMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_OPENDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_OPENYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_OPENHOUR, new Integer(12)); state.setAttribute(NEW_ASSIGNMENT_OPENMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_OPENAMPM, "PM"); // due date is shifted forward by 7 days t.setTime(t.getTime() + 7 * 24 * 60 * 60 * 1000); tB = t.breakdownLocal(); month = tB.getMonth(); day = tB.getDay(); year = tB.getYear(); // set the due time to be 5:00pm state.setAttribute(NEW_ASSIGNMENT_DUEMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_DUEDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_DUEYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_DUEHOUR, new Integer(5)); state.setAttribute(NEW_ASSIGNMENT_DUEMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_DUEAMPM, "PM"); // enable the close date by default state.setAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE, new Boolean(true)); // set the close time to be 5:00 pm, same as the due time by default state.setAttribute(NEW_ASSIGNMENT_CLOSEMONTH, new Integer(month)); state.setAttribute(NEW_ASSIGNMENT_CLOSEDAY, new Integer(day)); state.setAttribute(NEW_ASSIGNMENT_CLOSEYEAR, new Integer(year)); state.setAttribute(NEW_ASSIGNMENT_CLOSEHOUR, new Integer(5)); state.setAttribute(NEW_ASSIGNMENT_CLOSEMIN, new Integer(0)); state.setAttribute(NEW_ASSIGNMENT_CLOSEAMPM, "PM"); state.setAttribute(NEW_ASSIGNMENT_SECTION, "001"); state.setAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE, new Integer(Assignment.TEXT_AND_ATTACHMENT_ASSIGNMENT_SUBMISSION)); state.setAttribute(NEW_ASSIGNMENT_GRADE_TYPE, new Integer(Assignment.UNGRADED_GRADE_TYPE)); state.setAttribute(NEW_ASSIGNMENT_GRADE_POINTS, ""); state.setAttribute(NEW_ASSIGNMENT_DESCRIPTION, ""); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE, Boolean.FALSE.toString()); state.setAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE, Boolean.FALSE.toString()); // make the honor pledge not include as the default state.setAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE, (new Integer(Assignment.HONOR_PLEDGE_NONE)).toString()); state.setAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK, AssignmentService.GRADEBOOK_INTEGRATION_NO); state.setAttribute(NEW_ASSIGNMENT_ATTACHMENT, EntityManager.newReferenceList()); state.setAttribute(NEW_ASSIGNMENT_HIDE_OPTION_FLAG, new Boolean(false)); state.setAttribute(NEW_ASSIGNMENT_FOCUS, NEW_ASSIGNMENT_TITLE); state.removeAttribute(NEW_ASSIGNMENT_DESCRIPTION_EMPTY); // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } state.removeAttribute(NEW_ASSIGNMENT_RANGE); state.removeAttribute(NEW_ASSIGNMENT_GROUPS); // remove the edit assignment id if any state.removeAttribute(EDIT_ASSIGNMENT_ID); // remove the resubmit number state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); } // resetNewAssignment /** * construct a Hashtable using integer as the key and three character string of the month as the value */ private Hashtable monthTable() { Hashtable n = new Hashtable(); n.put(new Integer(1), rb.getString("jan")); n.put(new Integer(2), rb.getString("feb")); n.put(new Integer(3), rb.getString("mar")); n.put(new Integer(4), rb.getString("apr")); n.put(new Integer(5), rb.getString("may")); n.put(new Integer(6), rb.getString("jun")); n.put(new Integer(7), rb.getString("jul")); n.put(new Integer(8), rb.getString("aug")); n.put(new Integer(9), rb.getString("sep")); n.put(new Integer(10), rb.getString("oct")); n.put(new Integer(11), rb.getString("nov")); n.put(new Integer(12), rb.getString("dec")); return n; } // monthTable /** * construct a Hashtable using the integer as the key and grade type String as the value */ private Hashtable gradeTypeTable() { Hashtable n = new Hashtable(); n.put(new Integer(2), rb.getString("letter")); n.put(new Integer(3), rb.getString("points")); n.put(new Integer(4), rb.getString("pass")); n.put(new Integer(5), rb.getString("check")); n.put(new Integer(1), rb.getString("ungra")); return n; } // gradeTypeTable /** * construct a Hashtable using the integer as the key and submission type String as the value */ private Hashtable submissionTypeTable() { Hashtable n = new Hashtable(); n.put(new Integer(1), rb.getString("inlin")); n.put(new Integer(2), rb.getString("attaonly")); n.put(new Integer(3), rb.getString("inlinatt")); n.put(new Integer(4), rb.getString("nonelec")); return n; } // submissionTypeTable /** * Sort based on the given property */ public void doSort(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); setupSort(data, data.getParameters().getString("criteria")); } /** * setup sorting parameters * * @param criteria * String for sortedBy */ private void setupSort(RunData data, String criteria) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } } // doSort /** * Do sort by group title */ public void doSortbygrouptitle(RunData data) { setupSort(data, SORTED_BY_GROUP_TITLE); } // doSortbygrouptitle /** * Do sort by group description */ public void doSortbygroupdescription(RunData data) { setupSort(data, SORTED_BY_GROUP_DESCRIPTION); } // doSortbygroupdescription /** * Sort submission based on the given property */ public void doSort_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_SUBMISSION_BY))) { state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_SUBMISSION_ASC, asc); } } // doSort_submission /** * Sort submission based on the given property in instructor grade view */ public void doSort_grade_submission(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // we are changing the sort, so start from the first page again resetPaging(state); // get the ParameterParser from RunData ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); // current sorting sequence String asc = ""; if (!criteria.equals(state.getAttribute(SORTED_GRADE_SUBMISSION_BY))) { state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); //for content review default is desc if (criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW)) asc = Boolean.FALSE.toString(); else asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } else { // current sorting sequence state.setAttribute(SORTED_GRADE_SUBMISSION_BY, criteria); asc = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_GRADE_SUBMISSION_ASC, asc); } } // doSort_grade_submission public void doSort_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String criteria = params.getString("criteria"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Sort sort = dtp.getSort(); if (sort.getSort().equals(criteria)) { sort.setAscending(sort.isAscending() ? false : true); } else { sort.setSort(criteria); sort.setAscending(true); } break; } } } public void doPage_tags(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String page = params.getString("page"); String pageSize = params.getString("pageSize"); String providerId = params.getString(PROVIDER_ID); String savedText = params.getString("savedText"); state.setAttribute(VIEW_SUBMISSION_TEXT, savedText); String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); for (DecoratedTaggingProvider dtp : providers) { if (dtp.getProvider().getId().equals(providerId)) { Pager pager = dtp.getPager(); pager.setPageSize(Integer.valueOf(pageSize)); if (Pager.FIRST.equals(page)) { pager.setFirstItem(0); } else if (Pager.PREVIOUS.equals(page)) { pager.setFirstItem(pager.getFirstItem() - pager.getPageSize()); } else if (Pager.NEXT.equals(page)) { pager.setFirstItem(pager.getFirstItem() + pager.getPageSize()); } else if (Pager.LAST.equals(page)) { pager.setFirstItem((pager.getTotalItems() / pager .getPageSize()) * pager.getPageSize()); } break; } } } /** * the UserSubmission clas */ public class UserSubmission { /** * the User object */ User m_user = null; /** * the AssignmentSubmission object */ AssignmentSubmission m_submission = null; public UserSubmission(User u, AssignmentSubmission s) { m_user = u; m_submission = s; } /** * Returns the AssignmentSubmission object */ public AssignmentSubmission getSubmission() { return m_submission; } /** * Returns the User object */ public User getUser() { return m_user; } } /** * the AssignmentComparator clas */ private class AssignmentComparator implements Comparator { Collator collator = Collator.getInstance(); /** * the SessionState object */ SessionState m_state = null; /** * the criteria */ String m_criteria = null; /** * the criteria */ String m_asc = null; /** * the user */ User m_user = null; /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. */ public AssignmentComparator(SessionState state, String criteria, String asc) { m_state = state; m_criteria = criteria; m_asc = asc; } // constructor /** * constructor * * @param state * The state object * @param criteria * The sort criteria string * @param asc * The sort order string. TRUE_STRING if ascending; "false" otherwise. * @param user * The user object */ public AssignmentComparator(SessionState state, String criteria, String asc, User user) { m_state = state; m_criteria = criteria; m_asc = asc; m_user = user; } // constructor /** * caculate the range string for an assignment */ private String getAssignmentRange(Assignment a) { String rv = ""; if (a.getAccess().equals(Assignment.AssignmentAccess.SITE)) { // site assignment rv = rb.getString("range.allgroups"); } else { try { // get current site Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); for (Iterator k = a.getGroups().iterator(); k.hasNext();) { // announcement by group rv = rv.concat(site.getGroup((String) k.next()).getTitle()); } } catch (Exception ignore) { } } return rv; } // getAssignmentRange /** * implementing the compare function * * @param o1 * The first object * @param o2 * The second object * @return The compare result. 1 is o1 < o2; -1 otherwise */ public int compare(Object o1, Object o2) { int result = -1; if (m_criteria == null) { m_criteria = SORTED_BY_DEFAULT; } /** *********** for sorting assignments ****************** */ if (m_criteria.equals(SORTED_BY_DEFAULT)) { int s1 = ((Assignment) o1).getPosition_order(); int s2 = ((Assignment) o2).getPosition_order(); if ( s1 == s2 ) // we either have 2 assignments with no existing postion_order or a numbering error, so sort by duedate { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.equals(t2)) { t1 = ((Assignment) o1).getTimeCreated(); t2 = ((Assignment) o2).getTimeCreated(); } if (t1!=null && t2!=null && t1.before(t2)) { result = -1; } else { result = 1; } } else if ( s1 == 0 && s2 > 0 ) // order has not been set on this object, so put it at the bottom of the list { result = 1; } else if ( s2 == 0 && s1 > 0 ) // making sure assignments with no position_order stay at the bottom { result = -1; } else // 2 legitimate postion orders { result = (s1 < s2) ? -1 : 1; } } if (m_criteria.equals(SORTED_BY_TITLE)) { // sorted by the assignment title String s1 = ((Assignment) o1).getTitle(); String s2 = ((Assignment) o2).getTitle(); result = compareString(s1, s2); } else if (m_criteria.equals(SORTED_BY_SECTION)) { // sorted by the assignment section String s1 = ((Assignment) o1).getSection(); String s2 = ((Assignment) o2).getSection(); result = compareString(s1, s2); } else if (m_criteria.equals(SORTED_BY_DUEDATE)) { // sorted by the assignment due date Time t1 = ((Assignment) o1).getDueTime(); Time t2 = ((Assignment) o2).getDueTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_OPENDATE)) { // sorted by the assignment open Time t1 = ((Assignment) o1).getOpenTime(); Time t2 = ((Assignment) o2).getOpenTime(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_BY_ASSIGNMENT_STATUS)) { result = compareString(((Assignment) o1).getStatus(), ((Assignment) o2).getStatus()); } else if (m_criteria.equals(SORTED_BY_NUM_SUBMISSIONS)) { // sort by numbers of submissions // initialize int subNum1 = 0; int subNum2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted()) subNum1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted()) subNum2++; } result = (subNum1 > subNum2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_NUM_UNGRADED)) { // sort by numbers of ungraded submissions // initialize int ungraded1 = 0; int ungraded2 = 0; Iterator submissions1 = AssignmentService.getSubmissions((Assignment) o1).iterator(); while (submissions1.hasNext()) { AssignmentSubmission submission1 = (AssignmentSubmission) submissions1.next(); if (submission1.getSubmitted() && !submission1.getGraded()) ungraded1++; } Iterator submissions2 = AssignmentService.getSubmissions((Assignment) o2).iterator(); while (submissions2.hasNext()) { AssignmentSubmission submission2 = (AssignmentSubmission) submissions2.next(); if (submission2.getSubmitted() && !submission2.getGraded()) ungraded2++; } result = (ungraded1 > ungraded2) ? 1 : -1; } else if (m_criteria.equals(SORTED_BY_SUBMISSION_STATUS)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); result = compareString(submission1.getStatus(), submission2.getStatus()); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_GRADE)) { try { AssignmentSubmission submission1 = AssignmentService.getSubmission(((Assignment) o1).getId(), m_user); String grade1 = " "; if (submission1 != null && submission1.getGraded() && submission1.getGradeReleased()) { grade1 = submission1.getGrade(); } AssignmentSubmission submission2 = AssignmentService.getSubmission(((Assignment) o2).getId(), m_user); String grade2 = " "; if (submission2 != null && submission2.getGraded() && submission2.getGradeReleased()) { grade2 = submission2.getGrade(); } result = compareString(grade1, grade2); } catch (IdUnusedException e) { return 1; } catch (PermissionException e) { return 1; } } else if (m_criteria.equals(SORTED_BY_MAX_GRADE)) { String maxGrade1 = maxGrade(((Assignment) o1).getContent().getTypeOfGrade(), (Assignment) o1); String maxGrade2 = maxGrade(((Assignment) o2).getContent().getTypeOfGrade(), (Assignment) o2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = compareString(maxGrade1, maxGrade2); } } // group related sorting else if (m_criteria.equals(SORTED_BY_FOR)) { // sorted by the public view attribute String factor1 = getAssignmentRange((Assignment) o1); String factor2 = getAssignmentRange((Assignment) o2); result = compareString(factor1, factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_TITLE)) { // sorted by the group title String factor1 = ((Group) o1).getTitle(); String factor2 = ((Group) o2).getTitle(); result = compareString(factor1, factor2); } else if (m_criteria.equals(SORTED_BY_GROUP_DESCRIPTION)) { // sorted by the group description String factor1 = ((Group) o1).getDescription(); String factor2 = ((Group) o2).getDescription(); if (factor1 == null) { factor1 = ""; } if (factor2 == null) { factor2 = ""; } result = compareString(factor1, factor2); } /** ***************** for sorting submissions in instructor grade assignment view ************* */ else if(m_criteria.equals(SORTED_GRADE_SUBMISSION_CONTENTREVIEW)) { UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null ) { result = 1; } else { int score1 = u1.getSubmission().getReviewScore(); int score2 = u2.getSubmission().getReviewScore(); result = (new Integer(score1)).intValue() > (new Integer(score2)).intValue() ? 1 : -1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null || u1.getUser() == null || u2.getUser() == null ) { result = 1; } else { String lName1 = u1.getUser().getSortName(); String lName2 = u2.getUser().getSortName(); result = compareString(lName1, lName2); } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null || s1.getTimeSubmitted() == null) { result = -1; } else if (s2 == null || s2.getTimeSubmitted() == null) { result = 1; } else if (s1.getTimeSubmitted().before(s2.getTimeSubmitted())) { result = -1; } else { result = 1; } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_STATUS)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; String status1 = ""; String status2 = ""; if (u1 == null) { status1 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s1 = u1.getSubmission(); if (s1 == null) { status1 = rb.getString("listsub.nosub"); } else { status1 = s1.getStatus(); } } if (u2 == null) { status2 = rb.getString("listsub.nosub"); } else { AssignmentSubmission s2 = u2.getSubmission(); if (s2 == null) { status2 = rb.getString("listsub.nosub"); } else { status2 = s2.getStatus(); } } result = compareString(status1, status2); } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_GRADE)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); //sort by submission grade if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { String grade1 = s1.getGrade(); String grade2 = s2.getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((s1.getAssignment().getContent().getTypeOfGrade() == 3) && ((s2.getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } } } else if (m_criteria.equals(SORTED_GRADE_SUBMISSION_BY_RELEASED)) { // sort by submission status UserSubmission u1 = (UserSubmission) o1; UserSubmission u2 = (UserSubmission) o2; if (u1 == null || u2 == null) { result = -1; } else { AssignmentSubmission s1 = u1.getSubmission(); AssignmentSubmission s2 = u2.getSubmission(); if (s1 == null) { result = -1; } else if (s2 == null) { result = 1; } else { // sort by submission released String released1 = (new Boolean(s1.getGradeReleased())).toString(); String released2 = (new Boolean(s2.getGradeReleased())).toString(); result = compareString(released1, released2); } } } /****** for other sort on submissions **/ else if (m_criteria.equals(SORTED_SUBMISSION_BY_LASTNAME)) { // sorted by the submitters sort name User[] u1 = ((AssignmentSubmission) o1).getSubmitters(); User[] u2 = ((AssignmentSubmission) o2).getSubmitters(); if (u1 == null || u2 == null) { return 1; } else { String submitters1 = ""; String submitters2 = ""; for (int j = 0; j < u1.length; j++) { if (u1[j] != null && u1[j].getSortName() != null) { if (j > 0) { submitters1 = submitters1.concat("; "); } submitters1 = submitters1.concat("" + u1[j].getSortName()); } } for (int j = 0; j < u2.length; j++) { if (u2[j] != null && u2[j].getSortName() != null) { if (j > 0) { submitters2 = submitters2.concat("; "); } submitters2 = submitters2.concat(u2[j].getSortName()); } } result = compareString(submitters1, submitters2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_SUBMIT_TIME)) { // sorted by submission time Time t1 = ((AssignmentSubmission) o1).getTimeSubmitted(); Time t2 = ((AssignmentSubmission) o2).getTimeSubmitted(); if (t1 == null) { result = -1; } else if (t2 == null) { result = 1; } else if (t1.before(t2)) { result = -1; } else { result = 1; } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_STATUS)) { // sort by submission status result = compareString(((AssignmentSubmission) o1).getStatus(), ((AssignmentSubmission) o2).getStatus()); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_GRADE)) { // sort by submission grade String grade1 = ((AssignmentSubmission) o1).getGrade(); String grade2 = ((AssignmentSubmission) o2).getGrade(); if (grade1 == null) { grade1 = ""; } if (grade2 == null) { grade2 = ""; } // if scale is points if ((((AssignmentSubmission) o1).getAssignment().getContent().getTypeOfGrade() == 3) && ((((AssignmentSubmission) o2).getAssignment().getContent().getTypeOfGrade() == 3))) { if (grade1.equals("")) { result = -1; } else if (grade2.equals("")) { result = 1; } else { result = compareDouble(grade1, grade2); } } else { result = compareString(grade1, grade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_MAX_GRADE)) { Assignment a1 = ((AssignmentSubmission) o1).getAssignment(); Assignment a2 = ((AssignmentSubmission) o2).getAssignment(); String maxGrade1 = maxGrade(a1.getContent().getTypeOfGrade(), a1); String maxGrade2 = maxGrade(a2.getContent().getTypeOfGrade(), a2); try { // do integer comparation inside point grade type int max1 = Integer.parseInt(maxGrade1); int max2 = Integer.parseInt(maxGrade2); result = (max1 < max2) ? -1 : 1; } catch (NumberFormatException e) { // otherwise do an alpha-compare result = maxGrade1.compareTo(maxGrade2); } } else if (m_criteria.equals(SORTED_SUBMISSION_BY_RELEASED)) { // sort by submission released String released1 = (new Boolean(((AssignmentSubmission) o1).getGradeReleased())).toString(); String released2 = (new Boolean(((AssignmentSubmission) o2).getGradeReleased())).toString(); result = compareString(released1, released2); } else if (m_criteria.equals(SORTED_SUBMISSION_BY_ASSIGNMENT)) { // sort by submission's assignment String title1 = ((AssignmentSubmission) o1).getAssignment().getContent().getTitle(); String title2 = ((AssignmentSubmission) o2).getAssignment().getContent().getTitle(); result = compareString(title1, title2); } /*************** sort user by sort name ***************/ else if (m_criteria.equals(SORTED_USER_BY_SORTNAME)) { // sort by user's sort name String name1 = ((User) o1).getSortName(); String name2 = ((User) o2).getSortName(); result = compareString(name1, name2); } // sort ascending or descending if (!Boolean.valueOf(m_asc)) { result = -result; } return result; } /** * Compare two strings as double values. Deal with the case when either of the strings cannot be parsed as double value. * @param grade1 * @param grade2 * @return */ private int compareDouble(String grade1, String grade2) { int result; try { result = (new Double(grade1)).doubleValue() > (new Double(grade2)).doubleValue() ? 1 : -1; } catch (Exception formatException) { // in case either grade1 or grade2 cannot be parsed as Double result = compareString(grade1, grade2); } return result; } // compareDouble private int compareString(String s1, String s2) { int result; if (s1 == null && s2 == null) { result = 0; } else if (s2 == null) { result = 1; } else if (s1 == null) { result = -1; } else { result = collator.compare(s1.toLowerCase(), s2.toLowerCase()); } return result; } /** * get submission status */ private String getSubmissionStatus(AssignmentSubmission submission, Assignment assignment) { String status = ""; if (submission != null) if (submission.getSubmitted()) if (submission.getGraded() && submission.getGradeReleased()) status = rb.getString("grad3"); else if (submission.getReturned()) status = rb.getString("return") + " " + submission.getTimeReturned().toStringLocalFull(); else { status = rb.getString("submitt") + submission.getTimeSubmitted().toStringLocalFull(); if (submission.getTimeSubmitted().after(assignment.getDueTime())) status = status + rb.getString("late"); } else status = rb.getString("inpro"); else status = rb.getString("notsta"); return status; } // getSubmissionStatus /** * get assignment maximun grade available based on the assignment grade type * * @param gradeType * The int value of grade type * @param a * The assignment object * @return The max grade String */ private String maxGrade(int gradeType, Assignment a) { String maxGrade = ""; if (gradeType == -1) { // Grade type not set maxGrade = rb.getString("granotset"); } else if (gradeType == 1) { // Ungraded grade type maxGrade = rb.getString("nogra"); } else if (gradeType == 2) { // Letter grade type maxGrade = "A"; } else if (gradeType == 3) { // Score based grade type maxGrade = Integer.toString(a.getContent().getMaxGradePoint()); } else if (gradeType == 4) { // Pass/fail grade type maxGrade = rb.getString("pass2"); } else if (gradeType == 5) { // Grade type that only requires a check maxGrade = rb.getString("check2"); } return maxGrade; } // maxGrade } // DiscussionComparator /** * Fire up the permissions editor */ public void doPermissions(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); if (SiteService.allowUpdateSite((String) state.getAttribute(STATE_CONTEXT_STRING))) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.permissions.helper"); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); String siteRef = SiteService.siteReference(contextString); // setup for editing the permissions of the site for this tool, using the roles of this site, too state.setAttribute(PermissionsHelper.TARGET_REF, siteRef); // ... with this description state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperfor") + " " + SiteService.getSiteDisplay(contextString)); // ... showing only locks that are prpefixed with this state.setAttribute(PermissionsHelper.PREFIX, "asn."); // disable auto-updates while leaving the list view justDelivered(state); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } // switching back to assignment list view state.setAttribute(STATE_SELECTED_VIEW, MODE_LIST_ASSIGNMENTS); doList_assignments(data); } } // doPermissions /** * transforms the Iterator to Vector */ private Vector iterator_to_vector(Iterator l) { Vector v = new Vector(); while (l.hasNext()) { v.add(l.next()); } return v; } // iterator_to_vector /** * Implement this to return alist of all the resources that there are to page. Sort them as appropriate. */ protected List readResourcesPage(SessionState state, int first, int last) { List returnResources = (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS); PagingPosition page = new PagingPosition(first, last); page.validate(returnResources.size()); returnResources = returnResources.subList(page.getFirst() - 1, page.getLast()); return returnResources; } // readAllResources /* * (non-Javadoc) * * @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState) */ protected int sizeResources(SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); String contextString = (String) state.getAttribute(STATE_CONTEXT_STRING); // all the resources for paging List returnResources = new Vector(); boolean allowAddAssignment = AssignmentService.allowAddAssignment(contextString); if (mode.equalsIgnoreCase(MODE_LIST_ASSIGNMENTS)) { String view = ""; if (state.getAttribute(STATE_SELECTED_VIEW) != null) { view = (String) state.getAttribute(STATE_SELECTED_VIEW); } if (allowAddAssignment && view.equals(MODE_LIST_ASSIGNMENTS)) { // read all Assignments returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (allowAddAssignment && view.equals(MODE_STUDENT_VIEW) || (!allowAddAssignment && AssignmentService.allowAddSubmission((String) state .getAttribute(STATE_CONTEXT_STRING)))) { // in the student list view of assignments Iterator assignments = AssignmentService .getAssignmentsForContext(contextString); Time currentTime = TimeService.newTime(); while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); try { String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if (deleted == null || deleted.equals("")) { // show not deleted assignments Time openTime = a.getOpenTime(); if (openTime != null && currentTime.after(openTime) && !a.getDraft()) { returnResources.add(a); } } else if (deleted.equalsIgnoreCase(Boolean.TRUE.toString()) && (a.getContent().getTypeOfSubmission() != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) && AssignmentService.getSubmission(a.getReference(), (User) state .getAttribute(STATE_USER)) != null) { // and those deleted but not non-electronic assignments but the user has made submissions to them returnResources.add(a); } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } } else { // read all Assignments returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } state.setAttribute(HAS_MULTIPLE_ASSIGNMENTS, Boolean.valueOf(returnResources.size() > 1)); } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REORDER_ASSIGNMENT)) { returnResources = AssignmentService.getListAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING)); } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { Vector submissions = new Vector(); Vector assignments = iterator_to_vector(AssignmentService.getAssignmentsForContext((String) state .getAttribute(STATE_CONTEXT_STRING))); if (assignments.size() > 0) { // users = AssignmentService.allowAddSubmissionUsers (((Assignment)assignments.get(0)).getReference ()); } for (int j = 0; j < assignments.size(); j++) { Assignment a = (Assignment) assignments.get(j); //get the list of users which are allowed to grade this assignment List allowGradeAssignmentUsers = AssignmentService.allowGradeAssignmentUsers(a.getReference()); String deleted = a.getProperties().getProperty(ResourceProperties.PROP_ASSIGNMENT_DELETED); if ((deleted == null || deleted.equals("")) && (!a.getDraft()) && AssignmentService.allowGradeSubmission(a.getReference())) { try { List assignmentSubmissions = AssignmentService.getSubmissions(a); for (int k = 0; k < assignmentSubmissions.size(); k++) { AssignmentSubmission s = (AssignmentSubmission) assignmentSubmissions.get(k); if (s != null && (s.getSubmitted() || (s.getReturned() && (s.getTimeLastModified().before(s .getTimeReturned()))))) { // has been subitted or has been returned and not work on it yet User[] submitters = s.getSubmitters(); if (!allowGradeAssignmentUsers.contains(submitters[0])) { // only include the student submission submissions.add(s); } } // if-else } } catch (Exception e) { } } } returnResources = submissions; } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT)) { // range Collection groups = new Vector(); try { Assignment a = AssignmentService.getAssignment((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); // all submissions List submissions = AssignmentService.getSubmissions(a); // now are we view all sections/groups or just specific one? String allOrOneGroup = (String) state.getAttribute(VIEW_SUBMISSION_LIST_OPTION); if (allOrOneGroup.equals(rb.getString("gen.viewallgroupssections"))) { if (AssignmentService.allowAllGroups(contextString)) { // site range groups.add(SiteService.getSite(contextString)); } else { // get all groups user can grade groups = AssignmentService.getGroupsAllowGradeAssignment(contextString, a.getReference()); } } else { // filter out only those submissions from the selected-group members try { Group group = SiteService.getSite(contextString).getGroup(allOrOneGroup); groups.add(group); } catch (Exception e) { Log.warn("chef", e.getMessage() + " groupId=" + allOrOneGroup); } } // all users that can submit List allowAddSubmissionUsers = AssignmentService.allowAddSubmissionUsers((String) state.getAttribute(EXPORT_ASSIGNMENT_REF)); HashSet userIdSet = new HashSet(); for (Iterator iGroup=groups.iterator(); iGroup.hasNext();) { Object nGroup = iGroup.next(); String authzGroupRef = (nGroup instanceof Group)? ((Group) nGroup).getReference():((nGroup instanceof Site))?((Site) nGroup).getReference():null; if (authzGroupRef != null) { try { AuthzGroup group = AuthzGroupService.getAuthzGroup(authzGroupRef); Set grants = group.getUsers(); for (Iterator iUserIds = grants.iterator(); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); // don't show user multiple times if (!userIdSet.contains(userId)) { try { User u = UserDirectoryService.getUser(userId); // only include those users that can submit to this assignment if (u != null && allowAddSubmissionUsers.contains(u)) { boolean found = false; for (int i = 0; !found && i<submissions.size();i++) { AssignmentSubmission s = (AssignmentSubmission) submissions.get(i); if (s.getSubmitterIds().contains(userId)) { returnResources.add(new UserSubmission(u, s)); found = true; } } // add those users who haven't made any submissions if (!found) { // construct fake submissions for grading purpose if the user has right for grading if (AssignmentService.allowGradeSubmission(a.getReference())) { // temporarily allow the user to read and write from assignments (asn.revise permission) SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); AssignmentSubmissionEdit s = AssignmentService.addSubmission(contextString, a.getId(), userId); s.setSubmitted(true); s.setAssignment(a); AssignmentService.commitEdit(s); // update the UserSubmission list by adding newly created Submission object AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference()); returnResources.add(new UserSubmission(u, sub)); // clear the permission SecurityService.clearAdvisors(); } } } } catch (Exception e) { Log.warn("chef", this + e.toString() + " here userId = " + userId); } // add userId into set to prevent showing user multiple times userIdSet.add(userId); } } } catch (Exception eee) { Log.warn("chef", eee.getMessage() + " authGroupId=" + authzGroupRef); } } } } catch (IdUnusedException e) { addAlert(state, rb.getString("cannotfin3")); } catch (PermissionException e) { addAlert(state, rb.getString("youarenot14")); } } // sort them all String ascending = "true"; String sort = ""; ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_GRADE_ASSIGNMENT) && (sort == null || !sort.startsWith("sorted_grade_submission_by"))) { ascending = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_GRADE_SUBMISSION_BY); } else if (mode.equalsIgnoreCase(MODE_INSTRUCTOR_REPORT_SUBMISSIONS) && (sort == null || sort.startsWith("sorted_submission_by"))) { ascending = (String) state.getAttribute(SORTED_SUBMISSION_ASC); sort = (String) state.getAttribute(SORTED_SUBMISSION_BY); } else { ascending = (String) state.getAttribute(SORTED_ASC); sort = (String) state.getAttribute(SORTED_BY); } if ((returnResources.size() > 1) && !mode.equalsIgnoreCase(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { Collections.sort(returnResources, new AssignmentComparator(state, sort, ascending)); } // record the total item number state.setAttribute(STATE_PAGEING_TOTAL_ITEMS, returnResources); return returnResources.size(); } public void doView(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (!alertGlobalNavigation(state, data)) { // we are changing the view, so start with first page again. resetPaging(state); // clear search form doSearch_clear(data, null); String viewMode = data.getParameters().getString("view"); state.setAttribute(STATE_SELECTED_VIEW, viewMode); if (viewMode.equals(MODE_LIST_ASSIGNMENTS)) { doList_assignments(data); } else if (viewMode.equals(MODE_INSTRUCTOR_VIEW_STUDENTS_ASSIGNMENT)) { doView_students_assignment(data); } else if (viewMode.equals(MODE_INSTRUCTOR_REPORT_SUBMISSIONS)) { doReport_submissions(data); } else if (viewMode.equals(MODE_STUDENT_VIEW)) { doView_student(data); } // reset the global navigaion alert flag if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) != null) { state.removeAttribute(ALERT_GLOBAL_NAVIGATION); } } } // doView /** * put those variables related to 2ndToolbar into context */ private void add2ndToolbarFields(RunData data, Context context) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state.getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state.getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); context.put("selectedView", state.getAttribute(STATE_MODE)); } // add2ndToolbarFields /** * valid grade for point based type */ private void validPointGrade(SessionState state, String grade) { if (grade != null && !grade.equals("")) { if (grade.startsWith("-")) { // check for negative sign addAlert(state, rb.getString("plesuse3")); } else { int index = grade.indexOf("."); if (index != -1) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 if (!grade.equals(".")) { if (grade.length() > index + 2) { // if there are more than one decimal point addAlert(state, rb.getString("plesuse2")); } else { // decimal points is the only allowed character inside grade // replace it with '1', and try to parse the new String into int String gradeString = (grade.endsWith(".")) ? grade.substring(0, index).concat("0") : grade.substring(0, index).concat(grade.substring(index + 1)); try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { alertInvalidPoint(state, gradeString); } } } else { // grade is "." addAlert(state, rb.getString("plesuse1")); } } else { // There is no decimal point; should be int number String gradeString = grade + "0"; try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { alertInvalidPoint(state, gradeString); } } } } } // validPointGrade /** * valid grade for point based type */ private void validLetterGrade(SessionState state, String grade) { String VALID_CHARS_FOR_LETTER_GRADE = " ABCDEFGHIJKLMNOPQRSTUVWXYZ+-"; boolean invalid = false; if (grade != null) { grade = grade.toUpperCase(); for (int i = 0; i < grade.length() && !invalid; i++) { char c = grade.charAt(i); if (VALID_CHARS_FOR_LETTER_GRADE.indexOf(c) == -1) { invalid = true; } } if (invalid) { addAlert(state, rb.getString("plesuse0")); } } } private void alertInvalidPoint(SessionState state, String grade) { String VALID_CHARS_FOR_INT = "-01234567890"; boolean invalid = false; // case 1: contains invalid char for int for (int i = 0; i < grade.length() && !invalid; i++) { char c = grade.charAt(i); if (VALID_CHARS_FOR_INT.indexOf(c) == -1) { invalid = true; } } if (invalid) { addAlert(state, rb.getString("plesuse1")); } else { int maxInt = Integer.MAX_VALUE / 10; int maxDec = Integer.MAX_VALUE - maxInt * 10; // case 2: Due to our internal scaling, input String is larger than Integer.MAX_VALUE/10 addAlert(state, grade.substring(0, grade.length()-1) + "." + grade.substring(grade.length()-1) + " " + rb.getString("plesuse4") + maxInt + "." + maxDec + "."); } } /** * display grade properly */ private String displayGrade(SessionState state, String grade) { if (state.getAttribute(STATE_MESSAGE) == null) { if (grade != null && (grade.length() >= 1)) { if (grade.indexOf(".") != -1) { if (grade.startsWith(".")) { grade = "0".concat(grade); } else if (grade.endsWith(".")) { grade = grade.concat("0"); } } else { try { Integer.parseInt(grade); grade = grade.substring(0, grade.length() - 1) + "." + grade.substring(grade.length() - 1); } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } } else { grade = ""; } } return grade; } // displayGrade /** * scale the point value by 10 if there is a valid point grade */ private String scalePointGrade(SessionState state, String point) { validPointGrade(state, point); if (state.getAttribute(STATE_MESSAGE) == null) { if (point != null && (point.length() >= 1)) { // when there is decimal points inside the grade, scale the number by 10 // but only one decimal place is supported // for example, change 100.0 to 1000 int index = point.indexOf("."); if (index != -1) { if (index == 0) { // if the point is the first char, add a 0 for the integer part point = "0".concat(point.substring(1)); } else if (index < point.length() - 1) { // use scale integer for gradePoint point = point.substring(0, index) + point.substring(index + 1); } else { // decimal point is the last char point = point.substring(0, index) + "0"; } } else { // if there is no decimal place, scale up the integer by 10 point = point + "0"; } // filter out the "zero grade" if (point.equals("00")) { point = "0"; } } } return point; } // scalePointGrade /** * Processes formatted text that is coming back from the browser (from the formatted text editing widget). * * @param state * Used to pass in any user-visible alerts or errors when processing the text * @param strFromBrowser * The string from the browser * @param checkForFormattingErrors * Whether to check for formatted text errors - if true, look for errors in the formatted text. If false, accept the formatted text without looking for errors. * @return The formatted text */ private String processFormattedTextFromBrowser(SessionState state, String strFromBrowser, boolean checkForFormattingErrors) { StringBuilder alertMsg = new StringBuilder(); try { boolean replaceWhitespaceTags = true; String text = FormattedText.processFormattedText(strFromBrowser, alertMsg, checkForFormattingErrors, replaceWhitespaceTags); if (alertMsg.length() > 0) addAlert(state, alertMsg.toString()); return text; } catch (Exception e) { Log.warn("chef", this + ": ", e); return strFromBrowser; } } /** * Processes the given assignmnent feedback text, as returned from the user's browser. Makes sure that the Chef-style markup {{like this}} is properly balanced. */ private String processAssignmentFeedbackFromBrowser(SessionState state, String strFromBrowser) { if (strFromBrowser == null || strFromBrowser.length() == 0) return strFromBrowser; StringBuilder buf = new StringBuilder(strFromBrowser); int pos = -1; int numopentags = 0; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<ins>"); numopentags++; } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</ins>"); numopentags--; } while (numopentags > 0) { buf.append("</ins>"); numopentags--; } boolean checkForFormattingErrors = false; // so that grading isn't held up by formatting errors buf = new StringBuilder(processFormattedTextFromBrowser(state, buf.toString(), checkForFormattingErrors)); while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } /** * Called to deal with old Chef-style assignment feedback annotation, {{like this}}. * * @param value * A formatted text string that may contain {{}} style markup * @return HTML ready to for display on a browser */ public static String escapeAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); StringBuilder buf = new StringBuilder(value); int pos = -1; while ((pos = buf.indexOf("{{")) != -1) { buf.replace(pos, pos + "{{".length(), "<span class='highlight'>"); } while ((pos = buf.indexOf("}}")) != -1) { buf.replace(pos, pos + "}}".length(), "</span>"); } return FormattedText.escapeHtmlFormattedText(buf.toString()); } /** * Escapes the given assignment feedback text, to be edited as formatted text (perhaps using the formatted text widget) */ public static String escapeAssignmentFeedbackTextarea(String value) { if (value == null || value.length() == 0) return value; value = fixAssignmentFeedback(value); return FormattedText.escapeHtmlFormattedTextarea(value); } /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ private static String fixAssignmentFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuilder buf = new StringBuilder(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("<br/>")) != -1) { buf.replace(pos, pos + "<br/>".length(), "\n"); } // <span class='chefAlert'>( -> {{ while ((pos = buf.indexOf("<span class='chefAlert'>(")) != -1) { buf.replace(pos, pos + "<span class='chefAlert'>(".length(), "{{"); } // )</span> -> }} while ((pos = buf.indexOf(")</span>")) != -1) { buf.replace(pos, pos + ")</span>".length(), "}}"); } while ((pos = buf.indexOf("<ins>")) != -1) { buf.replace(pos, pos + "<ins>".length(), "{{"); } while ((pos = buf.indexOf("</ins>")) != -1) { buf.replace(pos, pos + "</ins>".length(), "}}"); } return buf.toString(); } // fixAssignmentFeedback /** * Apply the fix to pre 1.1.05 assignments submissions feedback. */ public static String showPrevFeedback(String value) { if (value == null || value.length() == 0) return value; StringBuilder buf = new StringBuilder(value); int pos = -1; // <br/> -> \n while ((pos = buf.indexOf("\n")) != -1) { buf.replace(pos, pos + "\n".length(), "<br />"); } return buf.toString(); } // showPrevFeedback private boolean alertGlobalNavigation(SessionState state, RunData data) { String mode = (String) state.getAttribute(STATE_MODE); ParameterParser params = data.getParameters(); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION) || mode.equals(MODE_STUDENT_PREVIEW_SUBMISSION) || mode.equals(MODE_STUDENT_VIEW_GRADE) || mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_DELETE_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION) || mode.equals(MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_VIEW_ASSIGNMENT) || mode.equals(MODE_INSTRUCTOR_REORDER_ASSIGNMENT)) { if (state.getAttribute(ALERT_GLOBAL_NAVIGATION) == null) { addAlert(state, rb.getString("alert.globalNavi")); state.setAttribute(ALERT_GLOBAL_NAVIGATION, Boolean.TRUE); if (mode.equals(MODE_STUDENT_VIEW_SUBMISSION)) { // retrieve the submission text (as formatted text) boolean checkForFormattingErrors = true; // the student is submitting something - so check for errors String text = processFormattedTextFromBrowser(state, params.getCleanString(VIEW_SUBMISSION_TEXT), checkForFormattingErrors); state.setAttribute(VIEW_SUBMISSION_TEXT, text); if (params.getString(VIEW_SUBMISSION_HONOR_PLEDGE_YES) != null) { state.setAttribute(VIEW_SUBMISSION_HONOR_PLEDGE_YES, "true"); } state.setAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT, rb.getString("gen.addatt")); // TODO: file picker to save in dropbox? -ggolden // User[] users = { UserDirectoryService.getCurrentUser() }; // state.setAttribute(ResourcesAction.STATE_SAVE_ATTACHMENT_IN_DROPBOX, users); } else if (mode.equals(MODE_INSTRUCTOR_NEW_EDIT_ASSIGNMENT)) { setNewAssignmentParameters(data, false); } else if (mode.equals(MODE_INSTRUCTOR_GRADE_SUBMISSION)) { readGradeForm(data, state, "read"); } return true; } } return false; } // alertGlobalNavigation /** * Dispatch function inside add submission page */ public void doRead_add_submission_form(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("cancel")) { // cancel doCancel_show_submission(data); } else if (option.equals("preview")) { // preview doPreview_submission(data); } else if (option.equals("save")) { // save draft doSave_submission(data); } else if (option.equals("post")) { // post doPost_submission(data); } else if (option.equals("revise")) { // done preview doDone_preview_submission(data); } else if (option.equals("attach")) { // attach ToolSession toolSession = SessionManager.getCurrentToolSession(); String userId = SessionManager.getCurrentSessionUserId(); String siteId = SiteService.getUserSiteId(userId); String collectionId = m_contentHostingService.getSiteCollection(siteId); toolSession.setAttribute(FilePickerHelper.DEFAULT_COLLECTION_ID, collectionId); doAttachments(data); } } /** * Set default score for all ungraded non electronic submissions * @param data */ public void doSet_defaultNotGradedNonElectronicScore(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); String grade = StringUtil.trimToNull(params.getString("defaultGrade")); if (grade == null) { addAlert(state, rb.getString("plespethe2")); } String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); try { // record the default grade setting for no-submission AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade); AssignmentService.commitEdit(aEdit); Assignment a = AssignmentService.getAssignment(assignmentId); if (a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { //for point-based grades validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } } if (grade != null && state.getAttribute(STATE_MESSAGE) == null) { // get the user list List submissions = AssignmentService.getSubmissions(a); for (int i = 0; i<submissions.size(); i++) { // get the submission object AssignmentSubmission submission = (AssignmentSubmission) submissions.get(i); if (submission.getSubmitted() && !submission.getGraded()) { // update the grades for those existing non-submissions AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setGrade(grade); sEdit.setGraded(true); AssignmentService.commitEdit(sEdit); } } } } catch (Exception e) { Log.warn("chef", e.toString()); } } /** * */ public void doSet_defaultNoSubmissionScore(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); String grade = StringUtil.trimToNull(params.getString("defaultGrade")); if (grade == null) { addAlert(state, rb.getString("plespethe2")); } String assignmentId = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); try { // record the default grade setting for no-submission AssignmentEdit aEdit = AssignmentService.editAssignment(assignmentId); aEdit.getPropertiesEdit().addProperty(GRADE_NO_SUBMISSION_DEFAULT_GRADE, grade); AssignmentService.commitEdit(aEdit); Assignment a = AssignmentService.getAssignment(assignmentId); if (a.getContent().getTypeOfGrade() == Assignment.SCORE_GRADE_TYPE) { //for point-based grades validPointGrade(state, grade); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getString("grad2")); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade); } } if (state.getAttribute(STATE_MESSAGE) == null) { grade = scalePointGrade(state, grade); } } if (grade != null && state.getAttribute(STATE_MESSAGE) == null) { // get the user list List userSubmissions = new Vector(); if (state.getAttribute(USER_SUBMISSIONS) != null) { userSubmissions = (List) state.getAttribute(USER_SUBMISSIONS); } // constructor a new UserSubmissions list List userSubmissionsNew = new Vector(); for (int i = 0; i<userSubmissions.size(); i++) { // get the UserSubmission object UserSubmission us = (UserSubmission) userSubmissions.get(i); User u = us.getUser(); AssignmentSubmission submission = us.getSubmission(); // check whether there is a submission associated if (submission == null) { AssignmentSubmissionEdit s = AssignmentService.addSubmission((String) state.getAttribute(STATE_CONTEXT_STRING), assignmentId, u.getId()); // submitted by without submit time s.setSubmitted(true); s.setGrade(grade); s.setGraded(true); s.setAssignment(a); AssignmentService.commitEdit(s); // update the UserSubmission list by adding newly created Submission object AssignmentSubmission sub = AssignmentService.getSubmission(s.getReference()); userSubmissionsNew.add(new UserSubmission(u, sub)); } else if (StringUtil.trimToNull(submission.getGrade()) == null) { // update the grades for those existing non-submissions AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setGrade(grade); sEdit.setSubmitted(true); sEdit.setGraded(true); AssignmentService.commitEdit(sEdit); userSubmissionsNew.add(new UserSubmission(u, AssignmentService.getSubmission(sEdit.getReference()))); } else if (StringUtil.trimToNull(submission.getGrade()) != null && !submission.getGraded()) { // correct the grade status if there is a grade but the graded is false AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(submission.getReference()); sEdit.setGraded(true); AssignmentService.commitEdit(sEdit); userSubmissionsNew.add(new UserSubmission(u, AssignmentService.getSubmission(sEdit.getReference()))); } else { // no change for this user userSubmissionsNew.add(us); } } state.setAttribute(USER_SUBMISSIONS, userSubmissionsNew); } } catch (Exception e) { Log.warn("chef", e.toString()); } } /** * * @return */ public void doUpload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String flow = params.getString("flow"); if (flow.equals("upload")) { // upload doUpload_all_upload(data); } else if (flow.equals("cancel")) { // cancel doCancel_upload_all(data); } } public void doUpload_all_upload(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String contextString = ToolManager.getCurrentPlacement().getContext(); String toolTitle = ToolManager.getTool(ASSIGNMENT_TOOL_ID).getTitle(); String aReference = (String) state.getAttribute(EXPORT_ASSIGNMENT_REF); String associateGradebookAssignment = null; boolean hasSubmissionText = false; boolean hasSubmissionAttachment = false; boolean hasGradeFile = false; boolean hasFeedbackText = false; boolean hasComment = false; boolean hasFeedbackAttachment = false; boolean releaseGrades = false; // check against the content elements selection if (params.getString("studentSubmissionText") != null) { // should contain student submission text information hasSubmissionText = true; } if (params.getString("studentSubmissionAttachment") != null) { // should contain student submission attachment information hasSubmissionAttachment = true; } if (params.getString("gradeFile") != null) { // should contain grade file hasGradeFile = true; } if (params.getString("feedbackTexts") != null) { // inline text hasFeedbackText = true; } if (params.getString("feedbackComments") != null) { // comments.txt should be available hasComment = true; } if (params.getString("feedbackAttachments") != null) { // feedback attachment hasFeedbackAttachment = true; } if (params.getString("release") != null) { // comments.xml should be available releaseGrades = params.getBoolean("release"); } state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT, Boolean.valueOf(hasSubmissionText)); state.setAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT, Boolean.valueOf(hasSubmissionAttachment)); state.setAttribute(UPLOAD_ALL_HAS_GRADEFILE, Boolean.valueOf(hasGradeFile)); state.setAttribute(UPLOAD_ALL_HAS_COMMENTS, Boolean.valueOf(hasComment)); state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT, Boolean.valueOf(hasFeedbackText)); state.setAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT, Boolean.valueOf(hasFeedbackAttachment)); state.setAttribute(UPLOAD_ALL_RELEASE_GRADES, Boolean.valueOf(releaseGrades)); if (!hasSubmissionText && !hasSubmissionAttachment && !hasFeedbackText && !hasGradeFile && !hasComment && !hasFeedbackAttachment) { // has to choose one upload feature addAlert(state, rb.getString("uploadall.alert.choose.element")); } else { // constructor the hashtable for all submission objects Hashtable submissionTable = new Hashtable(); Assignment assignment = null; List submissions = null; try { assignment = AssignmentService.getAssignment(aReference); associateGradebookAssignment = StringUtil.trimToNull(assignment.getProperties().getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); submissions = AssignmentService.getSubmissions(assignment); if (submissions != null) { Iterator sIterator = submissions.iterator(); while (sIterator.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); User[] users = s.getSubmitters(); if (users.length > 0 && users[0] != null) { submissionTable.put(users[0].getDisplayId(), new UploadGradeWrapper(s.getGrade(), s.getSubmittedText(), s.getFeedbackComment(), s.getSubmittedAttachments(), s.getFeedbackAttachments(), (s.getSubmitted() && s.getTimeSubmitted() != null)?s.getTimeSubmitted().toString():"", s.getFeedbackText())); } } } } catch (Exception e) { Log.warn("chef", e.toString()); } // see if the user uploaded a file FileItem fileFromUpload = null; String fileName = null; fileFromUpload = params.getFileItem("file"); String max_file_size_mb = ServerConfigurationService.getString("content.upload.max", "1"); int max_bytes = 1024 * 1024; try { max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024; } catch(Exception e) { // if unable to parse an integer from the value // in the properties file, use 1 MB as a default max_file_size_mb = "1"; max_bytes = 1024 * 1024; } if(fileFromUpload == null) { // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded")); } else if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0) { // no file addAlert(state, rb.getString("uploadall.alert.zipFile")); } else { byte[] fileData = fileFromUpload.get(); if(fileData.length >= max_bytes) { addAlert(state, rb.getString("uploadall.size") + " " + max_file_size_mb + "MB " + rb.getString("uploadall.exceeded")); } else if(fileData.length > 0) { ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(fileData)); ZipEntry entry; try { while ((entry=zin.getNextEntry()) != null) { String entryName = entry.getName(); if (!entry.isDirectory() && entryName.indexOf("/.") == -1) { if (entryName.endsWith("grades.csv")) { if (hasGradeFile) { // read grades.cvs from zip String result = StringUtil.trimToZero(readIntoString(zin)); String[] lines=null; if (result.indexOf("\r\n") != -1) lines = result.split("\r\n"); else if (result.indexOf("\r") != -1) lines = result.split("\r"); else if (result.indexOf("\n") != -1) lines = result.split("\n"); for (int i = 3; i<lines.length; i++) { // escape the first three header lines String[] items = lines[i].split(","); if (items.length > 4) { // has grade information try { User u = UserDirectoryService.getUserByEid(items[1]/*user eid*/); if (u != null) { UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(u.getDisplayId()); if (w != null) { String itemString = items[4]; int gradeType = assignment.getContent().getTypeOfGrade(); if (gradeType == Assignment.SCORE_GRADE_TYPE) { validPointGrade(state, itemString); } else { validLetterGrade(state, itemString); } if (state.getAttribute(STATE_MESSAGE) == null) { w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE?scalePointGrade(state, itemString):itemString); submissionTable.put(u.getDisplayId(), w); } } } } catch (Exception e ) { Log.warn("chef", e.toString()); } } } } } else { // get user eid part String userEid = ""; if (entryName.indexOf("/") != -1) { // remove the part of zip name userEid = entryName.substring(entryName.indexOf("/")+1); // get out the user name part if (userEid.indexOf("/") != -1) { userEid = userEid.substring(0, userEid.indexOf("/")); } // get the eid part if (userEid.indexOf("(") != -1) { userEid = userEid.substring(userEid.indexOf("(")+1, userEid.indexOf(")")); } userEid=StringUtil.trimToNull(userEid); } if (submissionTable.containsKey(userEid)) { if (hasComment && entryName.indexOf("comments") != -1) { // read the comments file String comment = getBodyTextFromZipHtml(zin); if (comment != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setComment(comment); submissionTable.put(userEid, r); } } if (hasFeedbackText && entryName.indexOf("feedbackText") != -1) { // upload the feedback text String text = getBodyTextFromZipHtml(zin); if (text != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setFeedbackText(text); submissionTable.put(userEid, r); } } if (hasSubmissionText && entryName.indexOf("_submissionText") != -1) { // upload the student submission text String text = getBodyTextFromZipHtml(zin); if (text != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setText(text); submissionTable.put(userEid, r); } } if (hasSubmissionAttachment) { // upload the submission attachment String submissionFolder = "/" + rb.getString("download.submission.attachment") + "/"; if ( entryName.indexOf(submissionFolder) != -1) { // clear the submission attachment first UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setSubmissionAttachments(new Vector()); submissionTable.put(userEid, r); uploadZipAttachments(state, submissionTable, zin, entry, entryName, userEid, "submission"); } } if (hasFeedbackAttachment) { // upload the feedback attachment String submissionFolder = "/" + rb.getString("download.feedback.attachment") + "/"; if ( entryName.indexOf(submissionFolder) != -1) { // clear the submission attachment first UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setFeedbackAttachments(new Vector()); submissionTable.put(userEid, r); uploadZipAttachments(state, submissionTable, zin, entry, entryName, userEid, "feedback"); } } // if this is a timestamp file if (entryName.indexOf("timestamp") != -1) { byte[] timeStamp = readIntoBytes(zin, entryName, entry.getSize()); UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setSubmissionTimestamp(new String(timeStamp)); submissionTable.put(userEid, r); } } } } } } catch (IOException e) { // uploaded file is not a valid archive addAlert(state, rb.getString("uploadall.alert.zipFile")); } } } if (state.getAttribute(STATE_MESSAGE) == null) { // update related submissions if (assignment != null && submissions != null) { Iterator sIterator = submissions.iterator(); while (sIterator.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) sIterator.next(); User[] users = s.getSubmitters(); if (users.length > 0 && users[0] != null) { String uName = users[0].getDisplayId(); if (submissionTable.containsKey(uName)) { // update the AssignmetnSubmission record try { AssignmentSubmissionEdit sEdit = AssignmentService.editSubmission(s.getReference()); UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(uName); // the submission text if (hasSubmissionText) { sEdit.setSubmittedText(w.getText()); } // the feedback text if (hasFeedbackText) { sEdit.setFeedbackText(w.getFeedbackText()); } // the submission attachment if (hasSubmissionAttachment) { sEdit.clearSubmittedAttachments(); for (Iterator attachments = w.getSubmissionAttachments().iterator(); attachments.hasNext();) { sEdit.addSubmittedAttachment((Reference) attachments.next()); } } // the feedback attachment if (hasFeedbackAttachment) { sEdit.clearFeedbackAttachments(); for (Iterator attachments = w.getFeedbackAttachments().iterator(); attachments.hasNext();) { sEdit.addFeedbackAttachment((Reference) attachments.next()); } } // the feedback comment if (hasComment) { sEdit.setFeedbackComment(w.getComment()); } // the grade file if (hasGradeFile) { // set grade String grade = StringUtil.trimToNull(w.getGrade()); sEdit.setGrade(grade); if (grade != null && !grade.equals(rb.getString("gen.nograd")) && !grade.equals("ungraded")) sEdit.setGraded(true); } // release or not if (sEdit.getGraded()) { sEdit.setGradeReleased(releaseGrades); sEdit.setReturned(releaseGrades); } else { sEdit.setGradeReleased(false); sEdit.setReturned(false); } if (releaseGrades && sEdit.getGraded()) { sEdit.setTimeReturned(TimeService.newTime()); } // if the current submission lacks timestamp while the timestamp exists inside the zip file if (StringUtil.trimToNull(w.getSubmissionTimeStamp()) != null && sEdit.getTimeSubmitted() == null) { sEdit.setTimeSubmitted(TimeService.newTimeGmt(w.getSubmissionTimeStamp())); sEdit.setSubmitted(true); } // for further information boolean graded = sEdit.getGraded(); String sReference = sEdit.getReference(); // commit AssignmentService.commitEdit(sEdit); if (releaseGrades && graded) { // update grade in gradebook if (associateGradebookAssignment != null) { integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, sReference, "update"); } } } catch (Exception ee) { Log.debug("chef", ee.toString()); } } } } } } } if (state.getAttribute(STATE_MESSAGE) == null) { // go back to the list of submissions view cleanUploadAllContext(state); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); } } /** * This is to get the submission or feedback attachment from the upload zip file into the submission object * @param state * @param submissionTable * @param zin * @param entry * @param entryName * @param userEid * @param submissionOrFeedback */ private void uploadZipAttachments(SessionState state, Hashtable submissionTable, ZipInputStream zin, ZipEntry entry, String entryName, String userEid, String submissionOrFeedback) { // upload all the files as instructor attachments to the submission for grading purpose String fName = entryName.substring(entryName.lastIndexOf("/") + 1, entryName.length()); ContentTypeImageService iService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); try { // get file extension for detecting content type // ignore those hidden files String extension = ""; if(!fName.contains(".") || (fName.contains(".") && fName.indexOf(".") != 0)) { // add the file as attachment ResourceProperties properties = m_contentHostingService.newResourceProperties(); properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, fName); String[] parts = fName.split("\\."); if(parts.length > 1) { extension = parts[parts.length - 1]; } String contentType = ((ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)).getContentType(extension); ContentResourceEdit attachment = m_contentHostingService.addAttachmentResource(fName); attachment.setContent(readIntoBytes(zin, entryName, entry.getSize())); attachment.setContentType(contentType); attachment.getPropertiesEdit().addAll(properties); m_contentHostingService.commitResource(attachment); UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); List attachments = submissionOrFeedback.equals("submission")?r.getSubmissionAttachments():r.getFeedbackAttachments(); attachments.add(EntityManager.newReference(attachment.getReference())); if (submissionOrFeedback.equals("submission")) { r.setSubmissionAttachments(attachments); } else { r.setFeedbackAttachments(attachments); } submissionTable.put(userEid, r); } } catch (Exception ee) { Log.warn("chef", ee.toString()); } } private String getBodyTextFromZipHtml(ZipInputStream zin) { String rv = ""; try { rv = StringUtil.trimToNull(readIntoString(zin)); } catch (IOException e) { Log.debug("chef", this + " " + e.toString()); } if (rv != null) { int start = rv.indexOf("<body>"); int end = rv.indexOf("</body>"); if (start != -1 && end != -1) { // get the text in between rv = rv.substring(start+6, end); } } return rv; } private byte[] readIntoBytes(ZipInputStream zin, String fName, long length) throws IOException { StringBuilder b = new StringBuilder(); byte[] buffer = new byte[4096]; File f = File.createTempFile("asgnup", "tmp"); FileOutputStream fout = new FileOutputStream(f); int len; while ((len = zin.read(buffer)) > 0) { fout.write(buffer, 0, len); } zin.closeEntry(); fout.close(); FileInputStream fis = new FileInputStream(f); FileChannel fc = fis.getChannel(); byte[] data = new byte[(int)(fc.size())]; // fc.size returns the size of the file which backs the channel ByteBuffer bb = ByteBuffer.wrap(data); fc.read(bb); //remove the file fc.close(); // The file channel needs to be closed before the deletion. f.delete(); return data; } private String readIntoString(ZipInputStream zin) throws IOException { StringBuilder buffer = new StringBuilder(); int size = 2048; byte[] data = new byte[2048]; while (true) { try { size = zin.read(data, 0, data.length); if (size > 0) { buffer.append(new String(data, 0, size)); } else { break; } } catch (IOException e) { Log.debug("chef", "readIntoString " + e.toString()); } } return buffer.toString(); } /** * * @return */ public void doCancel_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_GRADE_ASSIGNMENT); cleanUploadAllContext(state); } /** * clean the state variabled used by upload all process */ private void cleanUploadAllContext(SessionState state) { state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_SUBMISSION_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_ATTACHMENT); state.removeAttribute(UPLOAD_ALL_HAS_FEEDBACK_TEXT); state.removeAttribute(UPLOAD_ALL_HAS_GRADEFILE); state.removeAttribute(UPLOAD_ALL_HAS_COMMENTS); state.removeAttribute(UPLOAD_ALL_RELEASE_GRADES); } /** * Action is to preparing to go to the upload files */ public void doPrep_upload_all(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(STATE_MODE, MODE_INSTRUCTOR_UPLOAD_ALL); } // doPrep_upload_all /** * the UploadGradeWrapper class to be used for the "upload all" feature */ public class UploadGradeWrapper { /** * the grade */ String m_grade = null; /** * the text */ String m_text = null; /** * the submission attachment list */ List m_submissionAttachments = EntityManager.newReferenceList(); /** * the comment */ String m_comment = ""; /** * the timestamp */ String m_timeStamp=""; /** * the feedback text */ String m_feedbackText=""; /** * the feedback attachment list */ List m_feedbackAttachments = EntityManager.newReferenceList(); public UploadGradeWrapper(String grade, String text, String comment, List submissionAttachments, List feedbackAttachments, String timeStamp, String feedbackText) { m_grade = grade; m_text = text; m_comment = comment; m_submissionAttachments = submissionAttachments; m_feedbackAttachments = feedbackAttachments; m_feedbackText = feedbackText; m_timeStamp = timeStamp; } /** * Returns grade string */ public String getGrade() { return m_grade; } /** * Returns the text */ public String getText() { return m_text; } /** * Returns the comment string */ public String getComment() { return m_comment; } /** * Returns the submission attachment list */ public List getSubmissionAttachments() { return m_submissionAttachments; } /** * Returns the feedback attachment list */ public List getFeedbackAttachments() { return m_feedbackAttachments; } /** * submission timestamp * @return */ public String getSubmissionTimeStamp() { return m_timeStamp; } /** * feedback text/incline comment * @return */ public String getFeedbackText() { return m_feedbackText; } /** * set the grade string */ public void setGrade(String grade) { m_grade = grade; } /** * set the text */ public void setText(String text) { m_text = text; } /** * set the comment string */ public void setComment(String comment) { m_comment = comment; } /** * set the submission attachment list */ public void setSubmissionAttachments(List attachments) { m_submissionAttachments = attachments; } /** * set the attachment list */ public void setFeedbackAttachments(List attachments) { m_feedbackAttachments = attachments; } /** * set the submission timestamp */ public void setSubmissionTimestamp(String timeStamp) { m_timeStamp = timeStamp; } /** * set the feedback text */ public void setFeedbackText(String feedbackText) { m_feedbackText = feedbackText; } } private List<DecoratedTaggingProvider> initDecoratedProviders() { TaggingManager taggingManager = (TaggingManager) ComponentManager .get("org.sakaiproject.assignment.taggable.api.TaggingManager"); List<DecoratedTaggingProvider> providers = new ArrayList<DecoratedTaggingProvider>(); for (TaggingProvider provider : taggingManager.getProviders()) { providers.add(new DecoratedTaggingProvider(provider)); } return providers; } private List<DecoratedTaggingProvider> addProviders(Context context, SessionState state) { String mode = (String) state.getAttribute(STATE_MODE); List<DecoratedTaggingProvider> providers = (List) state .getAttribute(mode + PROVIDER_LIST); if (providers == null) { providers = initDecoratedProviders(); state.setAttribute(mode + PROVIDER_LIST, providers); } context.put("providers", providers); return providers; } private void addActivity(Context context, Assignment assignment) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("activity", assignmentActivityProducer .getActivity(assignment)); } private void addItem(Context context, AssignmentSubmission submission, String userId) { AssignmentActivityProducer assignmentActivityProducer = (AssignmentActivityProducer) ComponentManager .get("org.sakaiproject.assignment.taggable.api.AssignmentActivityProducer"); context.put("item", assignmentActivityProducer .getItem(submission, userId)); } private ContentReviewService contentReviewService; public String getReportURL(Long score) { getContentReviewService(); return contentReviewService.getIconUrlforScore(score); } private void getContentReviewService() { if (contentReviewService == null) { contentReviewService = (ContentReviewService) ComponentManager.get(ContentReviewService.class.getName()); } } }
fix to SAK-13023:Sakai generic jira: code can generate nullpointer exceptions (Static code review): Assignment-NPE git-svn-id: d213257099f21e50eb3b4c197ffbeb2264dc0174@41306 66ffb92e-73f9-0310-93c1-f5514f145a0a
assignment/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java
fix to SAK-13023:Sakai generic jira: code can generate nullpointer exceptions (Static code review): Assignment-NPE
Java
apache-2.0
cca6d413f1f0eab8b177514179d82e74fec3e4cf
0
newenter/saiku,qqming113/saiku,devgateway/ccrs-saiku,customme/saiku,OSBI/saiku,wtstengshen/saiku,standino/saiku,bisone/saiku,standino/saiku,devgateway/ccrs-saiku,wtstengshen/saiku,qqming113/saiku,qixiaobo/saiku-self,wwf830527/saiku,hengyuan/saiku,qixiaobo/saiku-self,standino/saiku,zegang/saiku,zegang/saiku,OSBI/saiku,dasbh/saiku,standino/saiku,qqming113/saiku,bisone/saiku,newenter/saiku,qqming113/saiku,standino/saiku,devgateway/ccrs-saiku,OSBI/saiku,dasbh/saiku,dasbh/saiku,customme/saiku,qqming113/saiku,zegang/saiku,bisone/saiku,OSBI/saiku,customme/saiku,wtstengshen/saiku,wtstengshen/saiku,hengyuan/saiku,wwf830527/saiku,devgateway/ccrs-saiku,wtstengshen/saiku,zegang/saiku,bisone/saiku,bisone/saiku,qqming113/saiku,devgateway/ccrs-saiku,standino/saiku,qixiaobo/saiku-self,dasbh/saiku,hengyuan/saiku,dasbh/saiku,OSBI/saiku,dasbh/saiku,newenter/saiku,wtstengshen/saiku,qixiaobo/saiku-self,zegang/saiku,hengyuan/saiku,zegang/saiku,devgateway/ccrs-saiku,customme/saiku,wwf830527/saiku,wwf830527/saiku,newenter/saiku,bisone/saiku,wwf830527/saiku
/* * Copyright 2012 OSBI Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.saiku.datasources.connection; import org.olap4j.OlapConnection; import org.olap4j.OlapWrapper; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; import mondrian.rolap.RolapConnection; import static org.saiku.datasources.connection.encrypt.CryptoUtil.decrypt; public class SaikuOlapConnection implements ISaikuConnection { private String name; private boolean initialized = false; private Properties properties; private OlapConnection olapConnection; private String username; private String password; private String passwordenc; public SaikuOlapConnection( String name, Properties props ) { this.name = name; this.properties = props; } public SaikuOlapConnection( Properties props ) { this.properties = props; this.name = props.getProperty( ISaikuConnection.NAME_KEY ); } public boolean connect() throws Exception { return connect( properties ); } private String decryptPassword(String password) { if ( password != null ) { return decrypt(password); } return null; } public boolean connect( Properties props ) throws Exception { this.username = props.getProperty( ISaikuConnection.USERNAME_KEY ); this.password = props.getProperty( ISaikuConnection.PASSWORD_KEY ); String driver = props.getProperty( ISaikuConnection.DRIVER_KEY ); this.passwordenc = props.getProperty(ISaikuConnection.PASSWORD_ENCRYPT_KEY); this.properties = props; String url = props.getProperty( ISaikuConnection.URL_KEY ); System.out.println( "name:" + name ); System.out.println( "driver:" + driver ); System.out.println( "url:" + url ); System.out.flush(); if(this.passwordenc != null && this.passwordenc.equals("true")){ this.password = decryptPassword(password); } if(url.contains("Mondrian=4")){ url=url.replace("Mondrian=4; ", ""); url= url.replace("jdbc:mondrian", "jdbc:mondrian4"); } if ( url.length() > 0 && url.charAt( url.length() - 1 ) != ';' ) { url += ";"; } if ( driver.equals( "mondrian.olap4j.MondrianOlap4jDriver" ) ) { if ( username != null && username.length() > 0 ) { url += "JdbcUser=" + username + ";"; } if ( password != null && password.length() > 0 ) { url += "JdbcPassword=" + password + ";"; } } Class.forName( driver ); Connection connection = DriverManager.getConnection(url, username, password); if(connection!=null) { final OlapWrapper wrapper = (OlapWrapper) connection; OlapConnection tmpolapConnection = wrapper.unwrap(OlapConnection.class); if (tmpolapConnection == null) { throw new Exception("Connection is null"); } System.out.println("Catalogs:" + tmpolapConnection.getOlapCatalogs().size()); olapConnection = tmpolapConnection; initialized = true; return true; } return false; } public boolean clearCache() throws Exception { if ( olapConnection.isWrapperFor( RolapConnection.class ) ) { System.out.println( "Clearing cache" ); RolapConnection rcon = olapConnection.unwrap( RolapConnection.class ); rcon.getCacheControl( null ).flushSchemaCache(); } return true; } public String getDatasourceType() { return ISaikuConnection.OLAP_DATASOURCE; } public boolean initialized() { return initialized; } public Connection getConnection() { return olapConnection; } public void setProperties( Properties props ) { properties = props; } public String getName() { return name; } public Properties getProperties() { return properties; } }
saiku-core/saiku-service/src/main/java/org/saiku/datasources/connection/SaikuOlapConnection.java
/* * Copyright 2012 OSBI Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.saiku.datasources.connection; import org.olap4j.OlapConnection; import org.olap4j.OlapWrapper; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; import mondrian.rolap.RolapConnection; import static org.saiku.datasources.connection.encrypt.CryptoUtil.decrypt; public class SaikuOlapConnection implements ISaikuConnection { private String name; private boolean initialized = false; private Properties properties; private OlapConnection olapConnection; private String username; private String password; private String passwordenc; public SaikuOlapConnection( String name, Properties props ) { this.name = name; this.properties = props; } public SaikuOlapConnection( Properties props ) { this.properties = props; this.name = props.getProperty( ISaikuConnection.NAME_KEY ); } public boolean connect() throws Exception { return connect( properties ); } private String decryptPassword(String password) { if ( password != null ) { return decrypt(password); } return null; } public boolean connect( Properties props ) throws Exception { this.username = props.getProperty( ISaikuConnection.USERNAME_KEY ); this.password = props.getProperty( ISaikuConnection.PASSWORD_KEY ); String driver = props.getProperty( ISaikuConnection.DRIVER_KEY ); this.passwordenc = props.getProperty(ISaikuConnection.PASSWORD_ENCRYPT_KEY); this.properties = props; String url = props.getProperty( ISaikuConnection.URL_KEY ); System.out.println( "name:" + name ); System.out.println( "driver:" + driver ); System.out.println( "url:" + url ); System.out.flush(); if(this.passwordenc != null && this.passwordenc.equals("true")){ this.password = decryptPassword(password); } if(url.contains("Mondrian=4")){ url=url.replace("Mondrian=4; ", ""); url= url.replace("jdbc:mondrian", "jdbc:mondrian4"); } if ( url.length() > 0 && url.charAt( url.length() - 1 ) != ';' ) { url += ";"; } if ( driver.equals( "mondrian.olap4j.MondrianOlap4jDriver" ) ) { if ( username != null && username.length() > 0 ) { url += "JdbcUser=" + username + ";"; } if ( password != null && password.length() > 0 ) { url += "JdbcPassword=" + password + ";"; } } Class.forName( driver ); Connection object = DriverManager.getConnection(url, username, password); OlapConnection connection = null; connection = (OlapConnection) DriverManager.getConnection(url, username, password); if(connection!=null) { final OlapWrapper wrapper = connection; OlapConnection tmpolapConnection = (OlapConnection) wrapper.unwrap(OlapConnection.class); if (tmpolapConnection == null) { throw new Exception("Connection is null"); } System.out.println("Catalogs:" + tmpolapConnection.getOlapCatalogs().size()); olapConnection = tmpolapConnection; initialized = true; return true; } return false; } public boolean clearCache() throws Exception { if ( olapConnection.isWrapperFor( RolapConnection.class ) ) { System.out.println( "Clearing cache" ); RolapConnection rcon = olapConnection.unwrap( RolapConnection.class ); rcon.getCacheControl( null ).flushSchemaCache(); } return true; } public String getDatasourceType() { return ISaikuConnection.OLAP_DATASOURCE; } public boolean initialized() { return initialized; } public Connection getConnection() { return olapConnection; } public void setProperties( Properties props ) { properties = props; } public String getName() { return name; } public Properties getProperties() { return properties; } }
Remove unused connection object.
saiku-core/saiku-service/src/main/java/org/saiku/datasources/connection/SaikuOlapConnection.java
Remove unused connection object.
Java
apache-2.0
0556943f274fd32844fcde9f711eb43ed66d8b81
0
consulo/consulo,consulo/consulo,consulo/consulo,consulo/consulo,consulo/consulo,consulo/consulo
/* * Copyright 2013-2021 consulo.io * * 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 consulo.container.plugin; import javax.annotation.Nonnull; import java.util.Collections; import java.util.Set; /** * @author VISTALL * @since 24/10/2021 */ public final class PluginPermissionDescriptor { private final PluginPermissionType myType; private final Set<String> myOptions; public PluginPermissionDescriptor(@Nonnull PluginPermissionType type, @Nonnull Set<String> options) { myType = type; myOptions = Collections.unmodifiableSet(options); } @Nonnull public PluginPermissionType getType() { return myType; } @Nonnull public Set<String> getOptions() { return myOptions; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PluginPermissionDescriptor that = (PluginPermissionDescriptor)o; if (myType != that.myType) return false; if (!myOptions.equals(that.myOptions)) return false; return true; } @Override public int hashCode() { int result = myType.hashCode(); result = 31 * result + myOptions.hashCode(); return result; } @Override public String toString() { return "PluginPermissionDescriptor{" + "myType=" + myType + ", myOptions=" + myOptions + '}'; } }
modules/boot/container-api/src/main/java/consulo/container/plugin/PluginPermissionDescriptor.java
/* * Copyright 2013-2021 consulo.io * * 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 consulo.container.plugin; import javax.annotation.Nonnull; import java.util.Collections; import java.util.Set; /** * @author VISTALL * @since 24/10/2021 */ public final class PluginPermissionDescriptor { private final PluginPermissionType myType; private final Set<String> myOptions; public PluginPermissionDescriptor(@Nonnull PluginPermissionType type, @Nonnull Set<String> options) { myType = type; myOptions = Collections.unmodifiableSet(options); } @Nonnull public PluginPermissionType getType() { return myType; } @Nonnull public Set<String> getOptions() { return myOptions; } }
add data methods
modules/boot/container-api/src/main/java/consulo/container/plugin/PluginPermissionDescriptor.java
add data methods
Java
apache-2.0
b37847710edec27e0be77f6f70094e1ba1bc48ff
0
SAGROUP2/apps-android-wikipedia,wikimedia/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,SAGROUP2/apps-android-wikipedia,SAGROUP2/apps-android-wikipedia,anirudh24seven/apps-android-wikipedia,dbrant/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,dbrant/apps-android-wikipedia,anirudh24seven/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,anirudh24seven/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,anirudh24seven/apps-android-wikipedia,SAGROUP2/apps-android-wikipedia,dbrant/apps-android-wikipedia,SAGROUP2/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,anirudh24seven/apps-android-wikipedia,wikimedia/apps-android-wikipedia,Duct-and-rice/KrswtkhrWiki4Android,wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia
package org.wikipedia.page.snippet; import android.content.DialogInterface; import android.content.res.Resources; import android.graphics.Bitmap; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.IntegerRes; import android.support.annotation.NonNull; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import com.appenguin.onboarding.ToolTip; import org.wikipedia.drawable.DrawableUtil; import org.wikipedia.page.ImageLicense; import org.wikipedia.page.ImageLicenseFetchTask; import org.wikipedia.bridge.CommunicationBridge; import org.wikipedia.page.NoDimBottomSheetDialog; import org.wikipedia.page.PageTitle; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.analytics.ShareAFactFunnel; import org.wikipedia.page.Page; import org.wikipedia.page.PageActivity; import org.wikipedia.page.PageProperties; import org.wikipedia.page.PageFragment; import org.wikipedia.settings.Prefs; import org.wikipedia.tooltip.ToolTipUtil; import org.wikipedia.activity.ActivityUtil; import org.wikipedia.util.ApiUtil; import org.wikipedia.util.FeedbackUtil; import org.wikipedia.util.ShareUtil; import org.json.JSONException; import org.json.JSONObject; import org.wikipedia.util.UriUtil; import org.wikipedia.util.log.L; import org.wikipedia.wiktionary.WiktionaryDialog; import java.util.Arrays; import java.util.Map; import static org.wikipedia.analytics.ShareAFactFunnel.ShareMode; /** * Let user choose between sharing as text or as image. */ public class ShareHandler { public static final String TAG = "ShareHandler"; private static final String PAYLOAD_PURPOSE_KEY = "purpose"; private static final String PAYLOAD_PURPOSE_SHARE = "share"; private static final String PAYLOAD_PURPOSE_DEFINE = "define"; private static final String PAYLOAD_PURPOSE_EDIT_HERE = "edit_here"; private static final String PAYLOAD_TEXT_KEY = "text"; @ColorRes private static final int SHARE_TOOL_TIP_COLOR = R.color.blue_liberal; private final PageActivity activity; private final CommunicationBridge bridge; private CompatActionMode webViewActionMode; private ShareAFactFunnel funnel; private void createFunnel() { WikipediaApp app = (WikipediaApp) activity.getApplicationContext(); final Page page = activity.getCurPageFragment().getPage(); final PageProperties pageProperties = page.getPageProperties(); funnel = new ShareAFactFunnel(app, page.getTitle(), pageProperties.getPageId(), pageProperties.getRevisionId()); } public ShareHandler(PageActivity activity, CommunicationBridge bridge) { this.activity = activity; this.bridge = bridge; bridge.addListener("onGetTextSelection", new CommunicationBridge.JSEventListener() { @Override public void onMessage(String messageType, JSONObject messagePayload) { String purpose = messagePayload.optString(PAYLOAD_PURPOSE_KEY, ""); String text = messagePayload.optString(PAYLOAD_TEXT_KEY, ""); switch (purpose) { case PAYLOAD_PURPOSE_SHARE: onSharePayload(text); break; case PAYLOAD_PURPOSE_DEFINE: onDefinePayload(text); break; case PAYLOAD_PURPOSE_EDIT_HERE: onEditHerePayload(messagePayload.optInt("sectionID", 0), text); break; default: L.d("Unknown purpose=" + purpose); } } }); } public void showWiktionaryDefinition(String text) { PageTitle title = activity.getCurPageFragment().getTitle(); activity.showBottomSheet(WiktionaryDialog.newInstance(title, text)); } private void onSharePayload(String text) { if (funnel == null) { createFunnel(); } shareSnippet(text); funnel.logShareTap(text); } private void onDefinePayload(String text) { showWiktionaryDefinition(text.toLowerCase()); } private void onEditHerePayload(int sectionID, String text) { activity.getCurPageFragment().getEditHandler().startEditingSection(sectionID, text); } private void showCopySnackbar() { FeedbackUtil.showMessage(activity, R.string.text_copied); } /** Call #setFunnel before #shareSnippet. */ private void shareSnippet(CharSequence input) { final PageFragment curPageFragment = activity.getCurPageFragment(); if (curPageFragment == null) { return; } final String selectedText = sanitizeText(input.toString()); final PageTitle title = curPageFragment.getTitle(); (new ImageLicenseFetchTask(WikipediaApp.getInstance().getAPIForSite(title.getSite()), title.getSite(), new PageTitle("File:" + curPageFragment.getPage().getPageProperties().getLeadImageName(), title.getSite())) { @Override public void onFinish(@NonNull Map<PageTitle, ImageLicense> result) { ImageLicense leadImageLicense = (ImageLicense) result.values().toArray()[0]; final SnippetImage snippetImage = new SnippetImage(activity, curPageFragment.getLeadImageBitmap(), curPageFragment.getLeadImageFocusY(), title.getDisplayText(), curPageFragment.getPage().isMainPage() ? "" : title.getDescription(), selectedText, leadImageLicense); final Bitmap snippetBitmap = snippetImage.drawBitmap(); activity.showBottomSheet(new PreviewDialog(activity, snippetBitmap, title, selectedText, funnel)); } @Override public void onCatch(Throwable caught) { Log.d(TAG, "Error fetching image license info for " + title.getDisplayText() + ": " + caught.getMessage(), caught); } }).execute(); } private static String sanitizeText(String selectedText) { return selectedText.replaceAll("\\[\\d+\\]", "") // [1] .replaceAll("\\(\\s*;\\s*", "\\(") // (; -> ( hacky way for IPA remnants .replaceAll("\\s{2,}", " ") .trim(); } /** * @param mode ActionMode under which this context is starting. */ public void onTextSelected(CompatActionMode mode) { webViewActionMode = mode; Menu menu = mode.getMenu(); MenuItem shareItem = menu.findItem(R.id.menu_text_select_share); handleSelection(menu, shareItem); } private void handleSelection(Menu menu, MenuItem shareItem) { if (WikipediaApp.getInstance().getOnboardingStateMachine().isShareTutorialEnabled()) { showShareOnboarding(shareItem); WikipediaApp.getInstance().getOnboardingStateMachine().setShareTutorial(); } // Provide our own listeners for the copy, define, and share buttons. shareItem.setOnMenuItemClickListener(new RequestTextSelectOnMenuItemClickListener(PAYLOAD_PURPOSE_SHARE)); MenuItem copyItem = menu.findItem(R.id.menu_text_select_copy); copyItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { activity.getCurPageFragment().getWebView().copyToClipboard(); showCopySnackbar(); leaveActionMode(); return true; } }); MenuItem defineItem = menu.findItem(R.id.menu_text_select_define); if (shouldEnableWiktionaryDialog()) { defineItem.setVisible(true); defineItem.setOnMenuItemClickListener(new RequestTextSelectOnMenuItemClickListener(PAYLOAD_PURPOSE_DEFINE)); } MenuItem editItem = menu.findItem(R.id.menu_text_edit_here); editItem.setOnMenuItemClickListener(new RequestTextSelectOnMenuItemClickListener(PAYLOAD_PURPOSE_EDIT_HERE)); if (!ApiUtil.hasJellyBean() || !activity.getCurPageFragment().getPage().isArticle()) { editItem.setVisible(false); } createFunnel(); funnel.logHighlight(); } private boolean shouldEnableWiktionaryDialog() { return Prefs.useRestBase() && isWiktionaryDialogEnabledForArticleLanguage(); } private boolean isWiktionaryDialogEnabledForArticleLanguage() { return Arrays.asList(WiktionaryDialog.getEnabledLanguages()) .contains(activity.getCurPageFragment().getTitle().getSite().languageCode()); } private void showShareOnboarding(MenuItem shareItem) { DrawableUtil.setTint(shareItem.getIcon(), getColor(SHARE_TOOL_TIP_COLOR)); postShowShareToolTip(shareItem); } private void postShowShareToolTip(final MenuItem shareItem) { // There doesn't seem to be good lifecycle event accessible at the time this called to // ensure the tool tip is shown after CAB animation. final View shareItemView = ActivityUtil.getMenuItemView(activity, shareItem); if (shareItemView != null) { int delay = getInteger(android.R.integer.config_longAnimTime); shareItemView.postDelayed(new Runnable() { @Override public void run() { showShareToolTip(shareItemView); } }, delay); } } private void showShareToolTip(View shareItemView) { ToolTipUtil.showToolTip(activity, shareItemView, R.layout.inflate_tool_tip_share, getColor(SHARE_TOOL_TIP_COLOR), ToolTip.Position.CENTER); } @ColorInt private int getColor(@ColorRes int id) { return getResources().getColor(id); } private int getInteger(@IntegerRes int id) { return getResources().getInteger(id); } private Resources getResources() { return activity.getResources(); } private void leaveActionMode() { if (hasWebViewActionMode()) { finishWebViewActionMode(); nullifyWebViewActionMode(); } } private boolean hasWebViewActionMode() { return webViewActionMode != null; } private void nullifyWebViewActionMode() { webViewActionMode = null; } private void finishWebViewActionMode() { webViewActionMode.finish(); } private class RequestTextSelectOnMenuItemClickListener implements MenuItem.OnMenuItemClickListener { @NonNull private final String purpose; RequestTextSelectOnMenuItemClickListener(@NonNull String purpose) { this.purpose = purpose; } @Override public boolean onMenuItemClick(MenuItem item) { requestTextSelection(purpose); leaveActionMode(); return true; } private void requestTextSelection(String purpose) { // send an event to the WebView that will make it return the // selected text (or first paragraph) back to us... try { JSONObject payload = new JSONObject(); payload.put(PAYLOAD_PURPOSE_KEY, purpose); bridge.sendMessage("getTextSelection", payload); } catch (JSONException e) { throw new RuntimeException(e); } } } } /** * A dialog to be displayed before sharing with two action buttons: * "Share as image", "Share as text". */ class PreviewDialog extends NoDimBottomSheetDialog { private boolean completed = false; PreviewDialog(final PageActivity activity, final Bitmap resultBitmap, final PageTitle title, final String selectedText, final ShareAFactFunnel funnel) { super(activity); View rootView = LayoutInflater.from(activity).inflate(R.layout.dialog_share_preview, null); setContentView(rootView); ImageView previewImage = (ImageView) rootView.findViewById(R.id.preview_img); previewImage.setImageBitmap(resultBitmap); rootView.findViewById(R.id.share_as_image_button) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String introText = activity.getString(R.string.snippet_share_intro, title.getDisplayText(), UriUtil.getUrlWithProvenance(activity, title, R.string.prov_share_image)); ShareUtil.shareImage(activity, resultBitmap, title.getDisplayText(), title.getDisplayText(), introText); funnel.logShareIntent(selectedText, ShareMode.image); completed = true; } }); rootView.findViewById(R.id.share_as_text_button) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String introText = activity.getString(R.string.snippet_share_intro, title.getDisplayText(), UriUtil.getUrlWithProvenance(activity, title, R.string.prov_share_text)); ShareUtil.shareText(activity, title.getDisplayText(), constructShareText(selectedText, introText)); funnel.logShareIntent(selectedText, ShareMode.text); completed = true; } }); setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { resultBitmap.recycle(); if (!completed) { funnel.logAbandoned(title.getDisplayText()); } } }); startExpanded(); } private String constructShareText(String selectedText, String introText) { return selectedText + "\n\n" + introText; } }
app/src/main/java/org/wikipedia/page/snippet/ShareHandler.java
package org.wikipedia.page.snippet; import android.content.DialogInterface; import android.content.res.Resources; import android.graphics.Bitmap; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.IntegerRes; import android.support.annotation.NonNull; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import com.appenguin.onboarding.ToolTip; import org.wikipedia.drawable.DrawableUtil; import org.wikipedia.page.ImageLicense; import org.wikipedia.page.ImageLicenseFetchTask; import org.wikipedia.bridge.CommunicationBridge; import org.wikipedia.page.NoDimBottomSheetDialog; import org.wikipedia.page.PageTitle; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.analytics.ShareAFactFunnel; import org.wikipedia.page.Page; import org.wikipedia.page.PageActivity; import org.wikipedia.page.PageProperties; import org.wikipedia.page.PageFragment; import org.wikipedia.settings.Prefs; import org.wikipedia.tooltip.ToolTipUtil; import org.wikipedia.activity.ActivityUtil; import org.wikipedia.util.ApiUtil; import org.wikipedia.util.FeedbackUtil; import org.wikipedia.util.ShareUtil; import org.json.JSONException; import org.json.JSONObject; import org.wikipedia.util.UriUtil; import org.wikipedia.util.log.L; import org.wikipedia.wiktionary.WiktionaryDialog; import java.util.Arrays; import java.util.Map; import static org.wikipedia.analytics.ShareAFactFunnel.ShareMode; /** * Let user choose between sharing as text or as image. */ public class ShareHandler { public static final String TAG = "ShareHandler"; private static final String PAYLOAD_PURPOSE_KEY = "purpose"; private static final String PAYLOAD_PURPOSE_SHARE = "share"; private static final String PAYLOAD_PURPOSE_DEFINE = "define"; private static final String PAYLOAD_PURPOSE_EDIT_HERE = "edit_here"; private static final String PAYLOAD_TEXT_KEY = "text"; @ColorRes private static final int SHARE_TOOL_TIP_COLOR = R.color.blue_liberal; private final PageActivity activity; private final CommunicationBridge bridge; private CompatActionMode webViewActionMode; private ShareAFactFunnel funnel; private void createFunnel() { WikipediaApp app = (WikipediaApp) activity.getApplicationContext(); final Page page = activity.getCurPageFragment().getPage(); final PageProperties pageProperties = page.getPageProperties(); funnel = new ShareAFactFunnel(app, page.getTitle(), pageProperties.getPageId(), pageProperties.getRevisionId()); } public ShareHandler(PageActivity activity, CommunicationBridge bridge) { this.activity = activity; this.bridge = bridge; bridge.addListener("onGetTextSelection", new CommunicationBridge.JSEventListener() { @Override public void onMessage(String messageType, JSONObject messagePayload) { String purpose = messagePayload.optString(PAYLOAD_PURPOSE_KEY, ""); String text = messagePayload.optString(PAYLOAD_TEXT_KEY, ""); switch (purpose) { case PAYLOAD_PURPOSE_SHARE: onSharePayload(text); break; case PAYLOAD_PURPOSE_DEFINE: onDefinePayload(text); break; case PAYLOAD_PURPOSE_EDIT_HERE: onEditHerePayload(messagePayload.optInt("sectionID", 0), text); break; default: L.d("Unknown purpose=" + purpose); } } }); } public void showWiktionaryDefinition(String text) { PageTitle title = activity.getCurPageFragment().getTitle(); activity.showBottomSheet(WiktionaryDialog.newInstance(title, text)); } private void onSharePayload(String text) { if (funnel == null) { createFunnel(); } shareSnippet(text); funnel.logShareTap(text); } private void onDefinePayload(String text) { showWiktionaryDefinition(text.toLowerCase()); } private void onEditHerePayload(int sectionID, String text) { activity.getCurPageFragment().getEditHandler().startEditingSection(sectionID, text); } private void showCopySnackbar() { FeedbackUtil.showMessage(activity, R.string.text_copied); } /** Call #setFunnel before #shareSnippet. */ private void shareSnippet(CharSequence input) { final PageFragment curPageFragment = activity.getCurPageFragment(); if (curPageFragment == null) { return; } final String selectedText = sanitizeText(input.toString()); final PageTitle title = curPageFragment.getTitle(); (new ImageLicenseFetchTask(WikipediaApp.getInstance().getAPIForSite(title.getSite()), title.getSite(), new PageTitle("File:" + curPageFragment.getPage().getPageProperties().getLeadImageName(), title.getSite())) { @Override public void onFinish(@NonNull Map<PageTitle, ImageLicense> result) { ImageLicense leadImageLicense = (ImageLicense) result.values().toArray()[0]; final SnippetImage snippetImage = new SnippetImage(activity, curPageFragment.getLeadImageBitmap(), curPageFragment.getLeadImageFocusY(), title.getDisplayText(), curPageFragment.getPage().isMainPage() ? "" : title.getDescription(), selectedText, leadImageLicense); final Bitmap snippetBitmap = snippetImage.drawBitmap(); activity.showBottomSheet(new PreviewDialog(activity, snippetBitmap, title, selectedText, funnel)); } @Override public void onCatch(Throwable caught) { Log.d(TAG, "Error fetching image license info for " + title.getDisplayText() + ": " + caught.getMessage(), caught); } }).execute(); } private static String sanitizeText(String selectedText) { return selectedText.replaceAll("\\[\\d+\\]", "") // [1] .replaceAll("\\(\\s*;\\s*", "\\(") // (; -> ( hacky way for IPA remnants .replaceAll("\\s{2,}", " ") .trim(); } /** * @param mode ActionMode under which this context is starting. */ public void onTextSelected(CompatActionMode mode) { webViewActionMode = mode; Menu menu = mode.getMenu(); MenuItem shareItem = menu.findItem(R.id.menu_text_select_share); handleSelection(menu, shareItem); } private void handleSelection(Menu menu, MenuItem shareItem) { if (WikipediaApp.getInstance().getOnboardingStateMachine().isShareTutorialEnabled()) { showShareOnboarding(shareItem); WikipediaApp.getInstance().getOnboardingStateMachine().setShareTutorial(); } // Provide our own listeners for the copy, define, and share buttons. shareItem.setOnMenuItemClickListener(new RequestTextSelectOnMenuItemClickListener(PAYLOAD_PURPOSE_SHARE)); MenuItem copyItem = menu.findItem(R.id.menu_text_select_copy); copyItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { activity.getCurPageFragment().getWebView().copyToClipboard(); showCopySnackbar(); leaveActionMode(); return true; } }); MenuItem defineItem = menu.findItem(R.id.menu_text_select_define); if (shouldEnableWiktionaryDialog()) { defineItem.setVisible(true); defineItem.setOnMenuItemClickListener(new RequestTextSelectOnMenuItemClickListener(PAYLOAD_PURPOSE_DEFINE)); } MenuItem editItem = menu.findItem(R.id.menu_text_edit_here); editItem.setOnMenuItemClickListener(new RequestTextSelectOnMenuItemClickListener(PAYLOAD_PURPOSE_EDIT_HERE)); if (!ApiUtil.hasJellyBean() || !activity.getCurPageFragment().getPage().isArticle()) { editItem.setVisible(false); } createFunnel(); funnel.logHighlight(); } private boolean shouldEnableWiktionaryDialog() { return Prefs.useRestBase() && WikipediaApp.getInstance().isPreProdRelease() && isWiktionaryDialogEnabledForArticleLanguage(); } private boolean isWiktionaryDialogEnabledForArticleLanguage() { return Arrays.asList(WiktionaryDialog.getEnabledLanguages()) .contains(activity.getCurPageFragment().getTitle().getSite().languageCode()); } private void showShareOnboarding(MenuItem shareItem) { DrawableUtil.setTint(shareItem.getIcon(), getColor(SHARE_TOOL_TIP_COLOR)); postShowShareToolTip(shareItem); } private void postShowShareToolTip(final MenuItem shareItem) { // There doesn't seem to be good lifecycle event accessible at the time this called to // ensure the tool tip is shown after CAB animation. final View shareItemView = ActivityUtil.getMenuItemView(activity, shareItem); if (shareItemView != null) { int delay = getInteger(android.R.integer.config_longAnimTime); shareItemView.postDelayed(new Runnable() { @Override public void run() { showShareToolTip(shareItemView); } }, delay); } } private void showShareToolTip(View shareItemView) { ToolTipUtil.showToolTip(activity, shareItemView, R.layout.inflate_tool_tip_share, getColor(SHARE_TOOL_TIP_COLOR), ToolTip.Position.CENTER); } @ColorInt private int getColor(@ColorRes int id) { return getResources().getColor(id); } private int getInteger(@IntegerRes int id) { return getResources().getInteger(id); } private Resources getResources() { return activity.getResources(); } private void leaveActionMode() { if (hasWebViewActionMode()) { finishWebViewActionMode(); nullifyWebViewActionMode(); } } private boolean hasWebViewActionMode() { return webViewActionMode != null; } private void nullifyWebViewActionMode() { webViewActionMode = null; } private void finishWebViewActionMode() { webViewActionMode.finish(); } private class RequestTextSelectOnMenuItemClickListener implements MenuItem.OnMenuItemClickListener { @NonNull private final String purpose; RequestTextSelectOnMenuItemClickListener(@NonNull String purpose) { this.purpose = purpose; } @Override public boolean onMenuItemClick(MenuItem item) { requestTextSelection(purpose); leaveActionMode(); return true; } private void requestTextSelection(String purpose) { // send an event to the WebView that will make it return the // selected text (or first paragraph) back to us... try { JSONObject payload = new JSONObject(); payload.put(PAYLOAD_PURPOSE_KEY, purpose); bridge.sendMessage("getTextSelection", payload); } catch (JSONException e) { throw new RuntimeException(e); } } } } /** * A dialog to be displayed before sharing with two action buttons: * "Share as image", "Share as text". */ class PreviewDialog extends NoDimBottomSheetDialog { private boolean completed = false; PreviewDialog(final PageActivity activity, final Bitmap resultBitmap, final PageTitle title, final String selectedText, final ShareAFactFunnel funnel) { super(activity); View rootView = LayoutInflater.from(activity).inflate(R.layout.dialog_share_preview, null); setContentView(rootView); ImageView previewImage = (ImageView) rootView.findViewById(R.id.preview_img); previewImage.setImageBitmap(resultBitmap); rootView.findViewById(R.id.share_as_image_button) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String introText = activity.getString(R.string.snippet_share_intro, title.getDisplayText(), UriUtil.getUrlWithProvenance(activity, title, R.string.prov_share_image)); ShareUtil.shareImage(activity, resultBitmap, title.getDisplayText(), title.getDisplayText(), introText); funnel.logShareIntent(selectedText, ShareMode.image); completed = true; } }); rootView.findViewById(R.id.share_as_text_button) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String introText = activity.getString(R.string.snippet_share_intro, title.getDisplayText(), UriUtil.getUrlWithProvenance(activity, title, R.string.prov_share_text)); ShareUtil.shareText(activity, title.getDisplayText(), constructShareText(selectedText, introText)); funnel.logShareIntent(selectedText, ShareMode.text); completed = true; } }); setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { resultBitmap.recycle(); if (!completed) { funnel.logAbandoned(title.getDisplayText()); } } }); startExpanded(); } private String constructShareText(String selectedText, String introText) { return selectedText + "\n\n" + introText; } }
[facepalm] Enable Wiktionary popups in production. http://i.imgur.com/iWKad22.jpg?fb Change-Id: I5c7556fb504ba991ff8c3aae6ba4764282c1a86a
app/src/main/java/org/wikipedia/page/snippet/ShareHandler.java
[facepalm] Enable Wiktionary popups in production.
Java
apache-2.0
5a36cb17cb96e4d9429f0b894327cac35d49f855
0
SimonVT/cathode,SimonVT/cathode
/* * Copyright (C) 2015 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.database; import android.database.Cursor; import android.database.CursorIndexOutOfBoundsException; import android.provider.BaseColumns; import java.util.ArrayList; import java.util.List; /** * A mutable cursor implementation backed by an {@link java.util.ArrayList} of {@code Object}s. */ public class SimpleCursor extends AbsSimpleCursor { private final String[] columnNames; private List<Object[]> data = new ArrayList<Object[]>(); private final int columnCount; /** * Constructs a new cursor with the given initial capacity. * * @param columnNames names of the columns, the ordering of which * determines column ordering elsewhere in this cursor */ public SimpleCursor(String[] columnNames) { this.columnNames = columnNames; this.columnCount = columnNames.length; } /** * Constructs a SimpleCursor from the data in source. */ public SimpleCursor(Cursor source) { this.columnNames = source.getColumnNames(); this.columnCount = this.columnNames.length; final int columnCount = source.getColumnCount(); while (source.moveToNext()) { Object[] data = new Object[columnCount]; for (int i = 0; i < columnCount; i++) { final int type = source.getType(i); switch (type) { case Cursor.FIELD_TYPE_BLOB: data[i] = source.getBlob(i); break; case Cursor.FIELD_TYPE_FLOAT: data[i] = source.getFloat(i); break; case Cursor.FIELD_TYPE_INTEGER: data[i] = source.getLong(i); break; case Cursor.FIELD_TYPE_STRING: data[i] = source.getString(i); break; } } add(data); } } private Object get(int column) { if (column < 0 || column >= columnCount) { throw new CursorIndexOutOfBoundsException( "Requested column: " + column + ", # of columns: " + columnCount); } if (mPos < 0) { throw new CursorIndexOutOfBoundsException("Before first row."); } if (mPos >= data.size()) { throw new CursorIndexOutOfBoundsException("After last row."); } return data.get(mPos)[column]; } /** * Adds a new row to the end with the given column values. Not safe * for concurrent use. * * @param columnValues in the same order as the the column names specified * at cursor construction time * @throws IllegalArgumentException if {@code columnValues.length != * columnNames.length} */ public void add(Object[] columnValues) { if (columnValues.length != columnCount) { throw new IllegalArgumentException( "columnNames.length = " + columnCount + ", columnValues.length = " + columnValues.length); } data.add(columnValues); } public Object[] get() { return data.get(mPos); } /** * Adds a new row to the end with the given column values. Not safe * for concurrent use. * * @param columnValues in the same order as the the column names specified at cursor construction * time * @param position The position at which to insert columnValues * @throws IllegalArgumentException if {@code columnValues.length != columnNames.length} */ public void add(Object[] columnValues, int position) { if (columnValues.length != columnCount) { throw new IllegalArgumentException( "columnNames.length = " + columnCount + ", columnValues.length = " + columnValues.length); } data.add(position, columnValues); } /** * Removes the item at the specified position. */ public void remove(int position) { data.remove(position); } public void remove(long id) { if (hasColumn(BaseColumns._ID)) { final int idColumn = getColumnIndex(BaseColumns._ID); for (int position = 0; position < getCount(); position++) { Object[] values = data.get(position); final long rowId = Long.valueOf(values[idColumn].toString()); if (id == rowId) { data.remove(position); break; } } } } @Override public int getCount() { return data.size(); } @Override public String[] getColumnNames() { return columnNames; } public boolean hasColumn(String column) { for (String col : columnNames) { if (column.equals(col)) { return true; } } return false; } @Override public String getString(int column) { Object value = get(column); if (value == null) return null; return value.toString(); } @Override public short getShort(int column) { Object value = get(column); if (value == null) return 0; if (value instanceof Number) return ((Number) value).shortValue(); return Short.parseShort(value.toString()); } @Override public int getInt(int column) { Object value = get(column); if (value == null) return 0; if (value instanceof Number) return ((Number) value).intValue(); return Integer.parseInt(value.toString()); } @Override public long getLong(int column) { Object value = get(column); if (value == null) return 0; if (value instanceof Number) return ((Number) value).longValue(); return Long.parseLong(value.toString()); } @Override public float getFloat(int column) { Object value = get(column); if (value == null) return 0.0f; if (value instanceof Number) return ((Number) value).floatValue(); return Float.parseFloat(value.toString()); } @Override public double getDouble(int column) { Object value = get(column); if (value == null) return 0.0d; if (value instanceof Number) return ((Number) value).doubleValue(); return Double.parseDouble(value.toString()); } @Override public byte[] getBlob(int column) { Object value = get(column); return (byte[]) value; } @Override public int getType(int column) { return getTypeOfObject(get(column)); } public static int getTypeOfObject(Object obj) { if (obj == null) { return FIELD_TYPE_NULL; } else if (obj instanceof byte[]) { return FIELD_TYPE_BLOB; } else if (obj instanceof Float || obj instanceof Double) { return FIELD_TYPE_FLOAT; } else if (obj instanceof Long || obj instanceof Integer || obj instanceof Short || obj instanceof Byte) { return FIELD_TYPE_INTEGER; } else { return FIELD_TYPE_STRING; } } @Override public boolean isNull(int column) { return get(column) == null; } }
cathode/src/main/java/net/simonvt/cathode/database/SimpleCursor.java
/* * Copyright (C) 2015 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.database; import android.database.Cursor; import android.database.CursorIndexOutOfBoundsException; import android.provider.BaseColumns; import java.util.ArrayList; import java.util.List; /** * A mutable cursor implementation backed by an {@link java.util.ArrayList} of {@code Object}s. */ public class SimpleCursor extends AbsSimpleCursor { private final String[] columnNames; private List<Object[]> data = new ArrayList<Object[]>(); private final int columnCount; /** * Constructs a new cursor with the given initial capacity. * * @param columnNames names of the columns, the ordering of which * determines column ordering elsewhere in this cursor */ public SimpleCursor(String[] columnNames) { this.columnNames = columnNames; this.columnCount = columnNames.length; } /** * Constructs a SimpleCursor from the data in source. */ public SimpleCursor(Cursor source) { this.columnNames = source.getColumnNames(); this.columnCount = this.columnNames.length; final int columnCount = source.getColumnCount(); while (source.moveToNext()) { Object[] data = new Object[columnCount]; for (int i = 0; i < columnCount; i++) { final int type = source.getType(i); switch (type) { case Cursor.FIELD_TYPE_BLOB: data[i] = source.getBlob(i); break; case Cursor.FIELD_TYPE_FLOAT: data[i] = source.getFloat(i); break; case Cursor.FIELD_TYPE_INTEGER: data[i] = source.getLong(i); break; case Cursor.FIELD_TYPE_STRING: data[i] = source.getString(i); break; } } add(data); } } private Object get(int column) { if (column < 0 || column >= columnCount) { throw new CursorIndexOutOfBoundsException( "Requested column: " + column + ", # of columns: " + columnCount); } if (mPos < 0) { throw new CursorIndexOutOfBoundsException("Before first row."); } if (mPos >= data.size()) { throw new CursorIndexOutOfBoundsException("After last row."); } return data.get(mPos)[column]; } /** * Adds a new row to the end with the given column values. Not safe * for concurrent use. * * @param columnValues in the same order as the the column names specified * at cursor construction time * @throws IllegalArgumentException if {@code columnValues.length != * columnNames.length} */ public void add(Object[] columnValues) { if (columnValues.length != columnCount) { throw new IllegalArgumentException( "columnNames.length = " + columnCount + ", columnValues.length = " + columnValues.length); } data.add(columnValues); } public Object[] get() { return data.get(mPos); } /** * Adds a new row to the end with the given column values. Not safe * for concurrent use. * * @param columnValues in the same order as the the column names specified at cursor construction * time * @param position The position at which to insert columnValues * @throws IllegalArgumentException if {@code columnValues.length != columnNames.length} */ public void add(Object[] columnValues, int position) { if (columnValues.length != columnCount) { throw new IllegalArgumentException( "columnNames.length = " + columnCount + ", columnValues.length = " + columnValues.length); } data.add(position, columnValues); } /** * Removes the item at the specified position. */ public void remove(int position) { data.remove(position); } public void remove(long id) { if (hasColumn(BaseColumns._ID)) { final int idColumn = getColumnIndex(BaseColumns._ID); for (int position = 0; position < getCount(); position++) { final long rowId = getLong(idColumn); if (id == rowId) { data.remove(position); break; } } } } @Override public int getCount() { return data.size(); } @Override public String[] getColumnNames() { return columnNames; } public boolean hasColumn(String column) { for (String col : columnNames) { if (column.equals(col)) { return true; } } return false; } @Override public String getString(int column) { Object value = get(column); if (value == null) return null; return value.toString(); } @Override public short getShort(int column) { Object value = get(column); if (value == null) return 0; if (value instanceof Number) return ((Number) value).shortValue(); return Short.parseShort(value.toString()); } @Override public int getInt(int column) { Object value = get(column); if (value == null) return 0; if (value instanceof Number) return ((Number) value).intValue(); return Integer.parseInt(value.toString()); } @Override public long getLong(int column) { Object value = get(column); if (value == null) return 0; if (value instanceof Number) return ((Number) value).longValue(); return Long.parseLong(value.toString()); } @Override public float getFloat(int column) { Object value = get(column); if (value == null) return 0.0f; if (value instanceof Number) return ((Number) value).floatValue(); return Float.parseFloat(value.toString()); } @Override public double getDouble(int column) { Object value = get(column); if (value == null) return 0.0d; if (value instanceof Number) return ((Number) value).doubleValue(); return Double.parseDouble(value.toString()); } @Override public byte[] getBlob(int column) { Object value = get(column); return (byte[]) value; } @Override public int getType(int column) { return getTypeOfObject(get(column)); } public static int getTypeOfObject(Object obj) { if (obj == null) { return FIELD_TYPE_NULL; } else if (obj instanceof byte[]) { return FIELD_TYPE_BLOB; } else if (obj instanceof Float || obj instanceof Double) { return FIELD_TYPE_FLOAT; } else if (obj instanceof Long || obj instanceof Integer || obj instanceof Short || obj instanceof Byte) { return FIELD_TYPE_INTEGER; } else { return FIELD_TYPE_STRING; } } @Override public boolean isNull(int column) { return get(column) == null; } }
Fix removal by id always removing position 0, or not at all.
cathode/src/main/java/net/simonvt/cathode/database/SimpleCursor.java
Fix removal by id always removing position 0, or not at all.
Java
apache-2.0
ca7600e43e437f0ac31d781261248722d5851eeb
0
cushon/error-prone,cushon/error-prone,google/error-prone,cushon/error-prone,cushon/error-prone,google/error-prone
/* * Copyright 2011 The Error Prone 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.google.errorprone.matchers; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getLast; import static com.google.common.collect.Streams.stream; import static com.google.errorprone.suppliers.Suppliers.BOOLEAN_TYPE; import static com.google.errorprone.suppliers.Suppliers.INT_TYPE; import static com.google.errorprone.suppliers.Suppliers.JAVA_LANG_BOOLEAN_TYPE; import static com.google.errorprone.suppliers.Suppliers.STRING_TYPE; import static com.google.errorprone.suppliers.Suppliers.typeFromClass; import static com.google.errorprone.suppliers.Suppliers.typeFromString; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static com.google.errorprone.util.ASTHelpers.stripParentheses; import static java.util.Objects.requireNonNull; import com.google.common.base.VerifyException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.errorprone.VisitorState; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.google.errorprone.matchers.ChildMultiMatcher.MatchType; import com.google.errorprone.matchers.MethodVisibility.Visibility; import com.google.errorprone.matchers.method.MethodMatchers; import com.google.errorprone.matchers.method.MethodMatchers.AnyMethodMatcher; import com.google.errorprone.matchers.method.MethodMatchers.ConstructorMatcher; import com.google.errorprone.matchers.method.MethodMatchers.InstanceMethodMatcher; import com.google.errorprone.matchers.method.MethodMatchers.StaticMethodMatcher; import com.google.errorprone.predicates.TypePredicate; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssertTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ContinueTree; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.SynchronizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.util.Name; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.BiPredicate; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; /** * Static factory methods which make the DSL read more fluently. Since matchers are run in a tight * loop during compilation, performance is important. When assembling a matcher from the DSL, it's * best to construct it only once, by saving the resulting matcher as a static variable for example. * * @author alexeagle@google.com (Alex Eagle) */ public class Matchers { private Matchers() {} /** A matcher that matches any AST node. */ public static <T extends Tree> Matcher<T> anything() { return (t, state) -> true; } /** A matcher that matches no AST node. */ public static <T extends Tree> Matcher<T> nothing() { return (t, state) -> false; } /** Matches an AST node iff it does not match the given matcher. */ public static <T extends Tree> Matcher<T> not(Matcher<T> matcher) { return (t, state) -> !matcher.matches(t, state); } /** * Compose several matchers together, such that the composite matches an AST node iff all the * given matchers do. */ @SafeVarargs public static <T extends Tree> Matcher<T> allOf(final Matcher<? super T>... matchers) { return (t, state) -> { for (Matcher<? super T> matcher : matchers) { if (!matcher.matches(t, state)) { return false; } } return true; }; } /** * Compose several matchers together, such that the composite matches an AST node if any of the * given matchers do. */ public static <T extends Tree> Matcher<T> anyOf( final Iterable<? extends Matcher<? super T>> matchers) { return (t, state) -> { for (Matcher<? super T> matcher : matchers) { if (matcher.matches(t, state)) { return true; } } return false; }; } @SafeVarargs public static <T extends Tree> Matcher<T> anyOf(Matcher<? super T>... matchers) { // IntelliJ claims it can infer <Matcher<? super T>>, but blaze can't (b/132970194). return anyOf(Arrays.<Matcher<? super T>>asList(matchers)); } /** Matches if an AST node is an instance of the given class. */ public static <T extends Tree> Matcher<T> isInstance(java.lang.Class<?> klass) { return (t, state) -> klass.isInstance(t); } /** Matches an AST node of a given kind, for example, an Annotation or a switch block. */ public static <T extends Tree> Matcher<T> kindIs(Kind kind) { return (tree, state) -> tree.getKind() == kind; } /** Matches an AST node of a given kind, for example, an Annotation or a switch block. */ public static <T extends Tree> Matcher<T> kindAnyOf(Set<Kind> kinds) { return (tree, state) -> kinds.contains(tree.getKind()); } /** Matches an AST node which is the same object reference as the given node. */ public static <T extends Tree> Matcher<T> isSame(Tree t) { return (tree, state) -> tree == t; } /** Matches a static method. */ public static StaticMethodMatcher staticMethod() { return MethodMatchers.staticMethod(); } /** Matches an instance method. */ public static InstanceMethodMatcher instanceMethod() { return MethodMatchers.instanceMethod(); } /** Matches a static or instance method. */ public static AnyMethodMatcher anyMethod() { return MethodMatchers.anyMethod(); } /** Matches a constructor. */ public static ConstructorMatcher constructor() { return MethodMatchers.constructor(); } /** * Match a Tree based solely on the Symbol produced by {@link ASTHelpers#getSymbol(Tree)}. * * <p>If {@code getSymbol} returns {@code null}, the matcher returns false instead of calling * {@code pred}. */ public static <T extends Tree> Matcher<T> symbolMatcher(BiPredicate<Symbol, VisitorState> pred) { return (tree, state) -> { Symbol sym = getSymbol(tree); return sym != null && pred.test(sym, state); }; } /** Matches an AST node that represents a non-static field. */ public static Matcher<ExpressionTree> isInstanceField() { return symbolMatcher( (symbol, state) -> symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()); } /** Matches an AST node that represents a local variable or parameter. */ public static Matcher<ExpressionTree> isVariable() { return symbolMatcher( (symbol, state) -> symbol.getKind() == ElementKind.LOCAL_VARIABLE || symbol.getKind() == ElementKind.PARAMETER); } /** * Matches a compound assignment operator AST node which matches a given left-operand matcher, a * given right-operand matcher, and a specific compound assignment operator. * * @param operator Which compound assignment operator to match against. * @param leftOperandMatcher The matcher to apply to the left operand. * @param rightOperandMatcher The matcher to apply to the right operand. */ public static CompoundAssignment compoundAssignment( Kind operator, Matcher<ExpressionTree> leftOperandMatcher, Matcher<ExpressionTree> rightOperandMatcher) { Set<Kind> operators = new HashSet<>(1); operators.add(operator); return new CompoundAssignment(operators, leftOperandMatcher, rightOperandMatcher); } /** * Matches a compound assignment operator AST node which matches a given left-operand matcher, a * given right-operand matcher, and is one of a set of compound assignment operators. Does not * match compound assignment operators. * * @param operators Which compound assignment operators to match against. * @param receiverMatcher The matcher to apply to the receiver. * @param expressionMatcher The matcher to apply to the expression. */ public static CompoundAssignment compoundAssignment( Set<Kind> operators, Matcher<ExpressionTree> receiverMatcher, Matcher<ExpressionTree> expressionMatcher) { return new CompoundAssignment(operators, receiverMatcher, expressionMatcher); } /** * Matches when the receiver of an instance method is the same reference as a particular argument * to the method. For example, receiverSameAsArgument(1) would match {@code obj.method("", obj)} * * @param argNum The number of the argument to compare against (zero-based. */ public static Matcher<? super MethodInvocationTree> receiverSameAsArgument(final int argNum) { return (t, state) -> { List<? extends ExpressionTree> args = t.getArguments(); if (args.size() <= argNum) { return false; } ExpressionTree arg = args.get(argNum); JCExpression methodSelect = (JCExpression) t.getMethodSelect(); if (methodSelect instanceof JCFieldAccess) { JCFieldAccess fieldAccess = (JCFieldAccess) methodSelect; return ASTHelpers.sameVariable(fieldAccess.getExpression(), arg); } else if (methodSelect instanceof JCIdent) { // A bare method call: "equals(foo)". Receiver is implicitly "this". return "this".equals(arg.toString()); } return false; }; } public static Matcher<MethodInvocationTree> receiverOfInvocation( final Matcher<ExpressionTree> expressionTreeMatcher) { return (methodInvocationTree, state) -> { ExpressionTree receiver = ASTHelpers.getReceiver(methodInvocationTree); return receiver != null && expressionTreeMatcher.matches(receiver, state); }; } /** * Matches if the given annotation matcher matches all of or any of the annotations on this tree * node. * * @param matchType Whether to match if the matchers match any of or all of the annotations on * this tree. * @param annotationMatcher The annotation matcher to use. */ public static <T extends Tree> MultiMatcher<T, AnnotationTree> annotations( MatchType matchType, Matcher<AnnotationTree> annotationMatcher) { return new AnnotationMatcher<>(matchType, annotationMatcher); } /** Matches a class in which any of/all of its constructors match the given constructorMatcher. */ public static MultiMatcher<ClassTree, MethodTree> constructor( MatchType matchType, Matcher<MethodTree> constructorMatcher) { return new ConstructorOfClass(matchType, constructorMatcher); } // TODO(cushon): expunge public static Matcher<MethodInvocationTree> methodSelect( Matcher<ExpressionTree> methodSelectMatcher) { return new MethodInvocationMethodSelect(methodSelectMatcher); } public static Matcher<MethodInvocationTree> argument( final int position, final Matcher<ExpressionTree> argumentMatcher) { return new MethodInvocationArgument(position, argumentMatcher); } /** Matches if the given matcher matches all of/any of the arguments to this method invocation. */ public static MultiMatcher<MethodInvocationTree, ExpressionTree> hasArguments( MatchType matchType, Matcher<ExpressionTree> argumentMatcher) { return new HasArguments(matchType, argumentMatcher); } /** * Matches an AST node if it is a method invocation and the given matchers match. * * @param methodSelectMatcher matcher identifying the method being called * @param matchType how to match method arguments with {@code methodArgumentMatcher} * @param methodArgumentMatcher matcher applied to each method argument */ public static Matcher<ExpressionTree> methodInvocation( Matcher<ExpressionTree> methodSelectMatcher, MatchType matchType, Matcher<ExpressionTree> methodArgumentMatcher) { return new MethodInvocation(methodSelectMatcher, matchType, methodArgumentMatcher); } /** * Matches an AST node if it is a method invocation and the method select matches {@code * methodSelectMatcher}. Ignores any arguments. */ public static Matcher<ExpressionTree> methodInvocation( final Matcher<ExpressionTree> methodSelectMatcher) { return (expressionTree, state) -> { if (!(expressionTree instanceof MethodInvocationTree)) { return false; } MethodInvocationTree tree = (MethodInvocationTree) expressionTree; return methodSelectMatcher.matches(tree.getMethodSelect(), state); }; } public static Matcher<MethodInvocationTree> argumentCount(final int argumentCount) { return (t, state) -> t.getArguments().size() == argumentCount; } /** * Matches an AST node if its parent node is matched by the given matcher. For example, {@code * parentNode(kindIs(Kind.RETURN))} would match the {@code this} expression in {@code return * this;} */ public static <T extends Tree> Matcher<T> parentNode(Matcher<Tree> treeMatcher) { return (tree, state) -> { TreePath parent = requireNonNull(state.getPath().getParentPath()); return treeMatcher.matches(parent.getLeaf(), state.withPath(parent)); }; } /** * Matches an AST node if its type is a subtype of the given type. * * @param typeStr a string representation of the type, e.g., "java.util.AbstractList" */ public static <T extends Tree> Matcher<T> isSubtypeOf(String typeStr) { return new IsSubtypeOf<>(typeStr); } /** * Matches an AST node if its type is a subtype of the given type. * * @param type the type to check against */ public static <T extends Tree> Matcher<T> isSubtypeOf(Supplier<Type> type) { return new IsSubtypeOf<>(type); } /** * Matches an AST node if its type is a subtype of the given type. * * @param clazz a class representation of the type, e.g., Action.class. */ public static <T extends Tree> Matcher<T> isSubtypeOf(Class<?> clazz) { return new IsSubtypeOf<>(typeFromClass(clazz)); } /** Matches an AST node if it has the same erased type as the given type. */ public static <T extends Tree> Matcher<T> isSameType(Supplier<Type> type) { return new IsSameType<>(type); } /** Matches an AST node if it has the same erased type as the given type. */ public static <T extends Tree> Matcher<T> isSameType(String typeString) { return new IsSameType<>(typeString); } /** Matches an AST node if it has the same erased type as the given class. */ public static <T extends Tree> Matcher<T> isSameType(Class<?> clazz) { return new IsSameType<>(typeFromClass(clazz)); } /** * Match a Tree based solely on the type produced by {@link ASTHelpers#getType(Tree)}. * * <p>If {@code getType} returns {@code null}, the matcher returns false instead of calling {@code * pred}. */ public static <T extends Tree> Matcher<T> typePredicateMatcher(TypePredicate pred) { return (tree, state) -> { Type type = getType(tree); return type != null && pred.apply(type, state); }; } /** Matches an AST node if its type is an array type. */ public static <T extends Tree> Matcher<T> isArrayType() { return typePredicateMatcher((type, state) -> state.getTypes().isArray(type)); } /** Matches an AST node if its type is a primitive array type. */ public static <T extends Tree> Matcher<T> isPrimitiveArrayType() { return typePredicateMatcher( (type, state) -> state.getTypes().isArray(type) && state.getTypes().elemtype(type).isPrimitive()); } /** Matches an AST node if its type is a primitive type. */ public static <T extends Tree> Matcher<T> isPrimitiveType() { return typePredicateMatcher((type, state) -> type.isPrimitive()); } /** Matches an AST node if its type is either a primitive type or a {@code void} type. */ public static <T extends Tree> Matcher<T> isPrimitiveOrVoidType() { return typePredicateMatcher((type, state) -> type.isPrimitiveOrVoid()); } /** Matches an AST node if its type is a {@code void} type. */ public static <T extends Tree> Matcher<T> isVoidType() { return typePredicateMatcher( (type, state) -> state.getTypes().isSameType(type, state.getSymtab().voidType)); } /** * Matches an AST node if its type is a primitive type, or a boxed version of a primitive type. */ public static <T extends Tree> Matcher<T> isPrimitiveOrBoxedPrimitiveType() { return typePredicateMatcher( (type, state) -> state.getTypes().unboxedTypeOrType(type).isPrimitive()); } /** Matches an AST node if its type is a boxed primitive type. */ public static Matcher<ExpressionTree> isBoxedPrimitiveType() { return typePredicateMatcher( (type, state) -> !state.getTypes().isSameType(state.getTypes().unboxedType(type), Type.noType)); } /** Matches an AST node which is enclosed by a block node that matches the given matcher. */ public static <T extends Tree> Enclosing.Block<T> enclosingBlock(Matcher<BlockTree> matcher) { return new Enclosing.Block<>(matcher); } /** Matches an AST node which is enclosed by a class node that matches the given matcher. */ public static <T extends Tree> Enclosing.Class<T> enclosingClass(Matcher<ClassTree> matcher) { return new Enclosing.Class<>(matcher); } /** Matches an AST node which is enclosed by a method node that matches the given matcher. */ public static <T extends Tree> Enclosing.Method<T> enclosingMethod(Matcher<MethodTree> matcher) { return new Enclosing.Method<>(matcher); } /** * Matches an AST node that is enclosed by some node that matches the given matcher. * * <p>TODO(eaftan): This could be used instead of enclosingBlock and enclosingClass. */ public static Matcher<Tree> enclosingNode(Matcher<Tree> matcher) { return (t, state) -> { TreePath path = state.getPath().getParentPath(); while (path != null) { Tree node = path.getLeaf(); state = state.withPath(path); if (matcher.matches(node, state)) { return true; } path = path.getParentPath(); } return false; }; } private static boolean siblingStatement( int offset, Matcher<StatementTree> matcher, StatementTree statement, VisitorState state) { // TODO(cushon): walking arbitrarily far up to find a block tree often isn't what we want TreePath blockPath = state.findPathToEnclosing(BlockTree.class); if (blockPath == null) { return false; } BlockTree block = (BlockTree) blockPath.getLeaf(); List<? extends StatementTree> statements = block.getStatements(); int idx = statements.indexOf(statement); if (idx == -1) { return false; } idx += offset; if (idx < 0 || idx >= statements.size()) { return false; } StatementTree sibling = statements.get(idx); return matcher.matches(sibling, state.withPath(new TreePath(blockPath, sibling))); } /** * Matches a statement AST node if the following statement in the enclosing block matches the * given matcher. */ public static <T extends StatementTree> Matcher<T> nextStatement(Matcher<StatementTree> matcher) { return (statement, state) -> siblingStatement(/* offset= */ 1, matcher, statement, state); } /** * Matches a statement AST node if the previous statement in the enclosing block matches the given * matcher. */ public static <T extends StatementTree> Matcher<T> previousStatement( Matcher<StatementTree> matcher) { return (statement, state) -> siblingStatement(/* offset= */ -1, matcher, statement, state); } /** Matches a statement AST node if the statement is the last statement in the block. */ public static Matcher<StatementTree> isLastStatementInBlock() { return (statement, state) -> { // TODO(cushon): walking arbitrarily far up to find a block tree often isn't what we want TreePath blockPath = state.findPathToEnclosing(BlockTree.class); if (blockPath == null) { return false; } BlockTree block = (BlockTree) blockPath.getLeaf(); return getLast(block.getStatements()).equals(statement); }; } /** Matches an AST node if it is a literal other than null. */ public static Matcher<ExpressionTree> nonNullLiteral() { return (tree, state) -> { switch (tree.getKind()) { case MEMBER_SELECT: return ((MemberSelectTree) tree).getIdentifier().contentEquals("class"); case INT_LITERAL: case LONG_LITERAL: case FLOAT_LITERAL: case DOUBLE_LITERAL: case BOOLEAN_LITERAL: case CHAR_LITERAL: // fall through case STRING_LITERAL: return true; default: return false; } }; } /** * Matches a Literal AST node if it is a string literal with the given value. For example, {@code * stringLiteral("thing")} matches the literal {@code "thing"} */ public static Matcher<ExpressionTree> stringLiteral(String value) { return new StringLiteral(value); } /** * Matches a Literal AST node if it is a string literal which matches the given {@link Pattern}. * * @see #stringLiteral(String) */ public static Matcher<ExpressionTree> stringLiteral(Pattern pattern) { return new StringLiteral(pattern); } public static Matcher<ExpressionTree> booleanLiteral(boolean value) { return (expressionTree, state) -> expressionTree.getKind() == Kind.BOOLEAN_LITERAL && value == (Boolean) (((LiteralTree) expressionTree).getValue()); } /** * Matches the boolean constant ({@link Boolean#TRUE} or {@link Boolean#FALSE}) corresponding to * the given value. */ public static Matcher<ExpressionTree> booleanConstant(boolean value) { return (expressionTree, state) -> { if (expressionTree instanceof JCFieldAccess) { Symbol symbol = getSymbol(expressionTree); if (symbol.isStatic() && state.getTypes().unboxedTypeOrType(symbol.type).getTag() == TypeTag.BOOLEAN) { if (value) { return symbol.getSimpleName().contentEquals("TRUE"); } else { return symbol.getSimpleName().contentEquals("FALSE"); } } } return false; }; } /** * Ignores any number of parenthesis wrapping an expression and then applies the passed matcher to * that expression. For example, the passed matcher would be applied to {@code value} in {@code * (((value)))}. */ public static Matcher<ExpressionTree> ignoreParens(Matcher<ExpressionTree> innerMatcher) { return (tree, state) -> innerMatcher.matches(stripParentheses(tree), state); } public static Matcher<ExpressionTree> intLiteral(int value) { return (tree, state) -> { return tree.getKind() == Kind.INT_LITERAL && value == ((Integer) ((LiteralTree) tree).getValue()); }; } public static Matcher<ExpressionTree> classLiteral( final Matcher<? super ExpressionTree> classMatcher) { return (tree, state) -> { if (tree.getKind() == Kind.MEMBER_SELECT) { MemberSelectTree select = (MemberSelectTree) tree; return select.getIdentifier().contentEquals("class") && classMatcher.matches(select.getExpression(), state); } return false; }; } /** * Matches an Annotation AST node if the argument to the annotation with the given name has a * value which matches the given matcher. For example, {@code hasArgumentWithValue("value", * stringLiteral("one"))} matches {@code @Thing("one")} or {@code @Thing({"one", "two"})} or * {@code @Thing(value = "one")} */ public static Matcher<AnnotationTree> hasArgumentWithValue( String argumentName, Matcher<ExpressionTree> valueMatcher) { return new AnnotationHasArgumentWithValue(argumentName, valueMatcher); } /** Matches an Annotation AST node if an argument to the annotation does not exist. */ public static Matcher<AnnotationTree> doesNotHaveArgument(String argumentName) { return new AnnotationDoesNotHaveArgument(argumentName); } public static Matcher<AnnotationTree> isType(String annotationClassName) { return new AnnotationType(annotationClassName); } /** * Matches a {@link MethodInvocation} when the arguments at the two given indices are both the * same variable, as determined by {@link ASTHelpers#sameVariable}. * * @param index1 the index of the first actual parameter to test * @param index2 the index of the second actual parameter to test * @throws IndexOutOfBoundsException if the given indices are invalid */ public static Matcher<? super MethodInvocationTree> sameArgument(int index1, int index2) { return (tree, state) -> { List<? extends ExpressionTree> args = tree.getArguments(); return ASTHelpers.sameVariable(args.get(index1), args.get(index2)); }; } /** * Determines whether an expression has an annotation of the given type. This includes annotations * inherited from superclasses due to @Inherited. * * @param annotationClass the binary class name of the annotation (e.g. * "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") */ public static <T extends Tree> Matcher<T> hasAnnotation(String annotationClass) { Supplier<Set<Name>> name = VisitorState.memoize( state -> ImmutableSet.of(state.binaryNameFromClassname(annotationClass))); return (T tree, VisitorState state) -> !ASTHelpers.annotationsAmong(ASTHelpers.getDeclaredSymbol(tree), name.get(state), state) .isEmpty(); } /** * Determines if an expression has an annotation referred to by the given mirror. Accounts for * binary names and annotations inherited due to @Inherited. * * @param annotationMirror mirror referring to the annotation type */ public static Matcher<Tree> hasAnnotation(TypeMirror annotationMirror) { String annotationName = annotationMirror.toString(); return (Tree tree, VisitorState state) -> { JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(state.context); TypeElement typeElem = (TypeElement) javacEnv.getTypeUtils().asElement(annotationMirror); String name; if (typeElem != null) { // Get the binary name if possible ($ to separate nested members). See b/36160747 name = javacEnv.getElementUtils().getBinaryName(typeElem).toString(); } else { name = annotationName; } return ASTHelpers.hasAnnotation(ASTHelpers.getDeclaredSymbol(tree), name, state); }; } /** * Determines whether an expression has an annotation with the given simple name. This does not * include annotations inherited from superclasses due to @Inherited. * * @param simpleName the simple name of the annotation (e.g. "Nullable") */ public static <T extends Tree> Matcher<T> hasAnnotationWithSimpleName(String simpleName) { return (tree, state) -> ASTHelpers.hasDirectAnnotationWithSimpleName( ASTHelpers.getDeclaredSymbol(tree), simpleName); } /** * Determines whether an expression refers to a symbol that has an annotation of the given type. * This includes annotations inherited from superclasses due to @Inherited. * * @param annotationClass the binary class name of the annotation (e.g. * "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") */ public static <T extends Tree> Matcher<T> symbolHasAnnotation(String annotationClass) { return symbolMatcher( (symbol, state) -> ASTHelpers.hasAnnotation(symbol, annotationClass, state)); } /** * Determines whether an expression has an annotation of the given class. This includes * annotations inherited from superclasses due to @Inherited. * * @param inputClass The class of the annotation to look for (e.g, Produces.class). */ public static <T extends Tree> Matcher<T> hasAnnotation(Class<? extends Annotation> inputClass) { return (tree, state) -> ASTHelpers.hasAnnotation(ASTHelpers.getDeclaredSymbol(tree), inputClass, state); } /** * Determines whether an expression refers to a symbol that has an annotation of the given type. * This includes annotations inherited from superclasses due to @Inherited. * * @param inputClass The class of the annotation to look for (e.g, Produces.class). */ public static <T extends Tree> Matcher<T> symbolHasAnnotation( Class<? extends Annotation> inputClass) { return (tree, state) -> ASTHelpers.hasAnnotation(getSymbol(tree), inputClass, state); } /** * Matches if a method or any method it overrides has an annotation of the given type. JUnit 4's * {@code @Test}, {@code @Before}, and {@code @After} annotations behave this way. * * @param annotationClass the binary class name of the annotation (e.g. * "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") */ public static Matcher<MethodTree> hasAnnotationOnAnyOverriddenMethod(String annotationClass) { return (tree, state) -> { MethodSymbol methodSym = getSymbol(tree); if (methodSym == null) { return false; } if (ASTHelpers.hasAnnotation(methodSym, annotationClass, state)) { return true; } for (MethodSymbol method : ASTHelpers.findSuperMethods(methodSym, state.getTypes())) { if (ASTHelpers.hasAnnotation(method, annotationClass, state)) { return true; } } return false; }; } /** Matches a whitelisted method invocation that is known to never return null */ public static Matcher<ExpressionTree> methodReturnsNonNull() { return anyOf( instanceMethod().onDescendantOf("java.lang.Object").named("toString"), instanceMethod().onExactClass("java.lang.String"), staticMethod().onClass("java.lang.String"), instanceMethod().onExactClass("java.util.StringTokenizer").named("nextToken")); } public static Matcher<MethodTree> methodReturns(Matcher<? super Tree> returnTypeMatcher) { return (methodTree, state) -> { Tree returnTree = methodTree.getReturnType(); // Constructors have no return type. return returnTree != null && returnTypeMatcher.matches(returnTree, state); }; } public static Matcher<MethodTree> methodReturns(Supplier<Type> returnType) { return methodReturns(isSameType(returnType)); } /** Match a method that returns a non-primitive type. */ public static Matcher<MethodTree> methodReturnsNonPrimitiveType() { return methodReturns(not(isPrimitiveOrVoidType())); } /** * Match a method declaration with a specific name. * * @param methodName The name of the method to match, e.g., "equals" */ public static Matcher<MethodTree> methodIsNamed(String methodName) { return (methodTree, state) -> methodTree.getName().contentEquals(methodName); } /** * Match a method declaration that starts with a given string. * * @param prefix The prefix. */ public static Matcher<MethodTree> methodNameStartsWith(String prefix) { return (methodTree, state) -> methodTree.getName().toString().startsWith(prefix); } /** * Match a method declaration with a specific enclosing class and method name. * * @param className The fully-qualified name of the enclosing class, e.g. * "com.google.common.base.Preconditions" * @param methodName The name of the method to match, e.g., "checkNotNull" */ public static Matcher<MethodTree> methodWithClassAndName(String className, String methodName) { return (methodTree, state) -> getSymbol(methodTree).getEnclosingElement().getQualifiedName().contentEquals(className) && methodTree.getName().contentEquals(methodName); } /** * Matches an AST node that represents a method declaration, based on the list of * variableMatchers. Applies the variableMatcher at index n to the parameter at index n and * returns true iff they all match. Returns false if the number of variableMatchers provided does * not match the number of parameters. * * <p>If you pass no variableMatchers, this will match methods with no parameters. * * @param variableMatcher an array of matchers to apply to the parameters of the method */ @SafeVarargs public static Matcher<MethodTree> methodHasParameters( final Matcher<VariableTree>... variableMatcher) { return methodHasParameters(ImmutableList.copyOf(variableMatcher)); } /** * Matches an AST node that represents a method declaration, based on the list of * variableMatchers. Applies the variableMatcher at index n to the parameter at index n and * returns true iff they all match. Returns false if the number of variableMatchers provided does * not match the number of parameters. * * <p>If you pass no variableMatchers, this will match methods with no parameters. * * @param variableMatcher a list of matchers to apply to the parameters of the method */ public static Matcher<MethodTree> methodHasParameters( final List<Matcher<VariableTree>> variableMatcher) { return (methodTree, state) -> { if (methodTree.getParameters().size() != variableMatcher.size()) { return false; } int paramIndex = 0; for (Matcher<VariableTree> eachVariableMatcher : variableMatcher) { if (!eachVariableMatcher.matches(methodTree.getParameters().get(paramIndex++), state)) { return false; } } return true; }; } /** Matches if the given matcher matches all of/any of the parameters to this method. */ public static MultiMatcher<MethodTree, VariableTree> methodHasParameters( MatchType matchType, Matcher<VariableTree> parameterMatcher) { return new MethodHasParameters(matchType, parameterMatcher); } public static Matcher<MethodTree> methodHasVisibility(Visibility visibility) { return new MethodVisibility(visibility); } public static Matcher<MethodTree> methodIsConstructor() { return (methodTree, state) -> getSymbol(methodTree).isConstructor(); } /** * Matches a constructor declaration in a specific enclosing class. * * @param className The fully-qualified name of the enclosing class, e.g. * "com.google.common.base.Preconditions" */ public static Matcher<MethodTree> constructorOfClass(String className) { return (methodTree, state) -> { Symbol symbol = getSymbol(methodTree); return symbol.getEnclosingElement().getQualifiedName().contentEquals(className) && symbol.isConstructor(); }; } /** * Matches a class in which at least one method matches the given methodMatcher. * * @param methodMatcher A matcher on MethodTrees to run against all methods in this class. * @return True if some method in the class matches the given methodMatcher. */ public static Matcher<ClassTree> hasMethod(Matcher<MethodTree> methodMatcher) { return (t, state) -> { for (Tree member : t.getMembers()) { if (member instanceof MethodTree && methodMatcher.matches((MethodTree) member, state)) { return true; } } return false; }; } /** * Matches on the type of a VariableTree AST node. * * @param treeMatcher A matcher on the type of the variable. */ public static Matcher<VariableTree> variableType(Matcher<Tree> treeMatcher) { return (variableTree, state) -> treeMatcher.matches(variableTree.getType(), state); } /** * Matches on the initializer of a VariableTree AST node. * * @param expressionTreeMatcher A matcher on the initializer of the variable. */ public static Matcher<VariableTree> variableInitializer( Matcher<ExpressionTree> expressionTreeMatcher) { return (variableTree, state) -> { ExpressionTree initializer = variableTree.getInitializer(); return initializer != null && expressionTreeMatcher.matches(initializer, state); }; } /** * Matches if a {@link VariableTree} is a field declaration, as opposed to a local variable, enum * constant, parameter to a method, etc. */ public static Matcher<VariableTree> isField() { return (variableTree, state) -> ElementKind.FIELD == getSymbol(variableTree).getKind(); } /** Matches if a {@link ClassTree} is an enum declaration. */ public static Matcher<ClassTree> isEnum() { return (classTree, state) -> getSymbol(classTree).getKind() == ElementKind.ENUM; } /** * Matches an class based on whether it is nested in another class or method. * * @param kind The kind of nesting to match, eg ANONYMOUS, LOCAL, MEMBER, TOP_LEVEL */ public static Matcher<ClassTree> nestingKind(NestingKind kind) { return (classTree, state) -> kind == getSymbol(classTree).getNestingKind(); } /** * Matches a binary tree if the given matchers match the operands in either order. That is, * returns true if either: matcher1 matches the left operand and matcher2 matches the right * operand or matcher2 matches the left operand and matcher1 matches the right operand */ public static Matcher<BinaryTree> binaryTree( Matcher<ExpressionTree> matcher1, Matcher<ExpressionTree> matcher2) { return (t, state) -> null != ASTHelpers.matchBinaryTree(t, Arrays.asList(matcher1, matcher2), state); } /** * Matches any AST that contains an identifier with a certain property. This matcher can be used, * for instance, to locate identifiers with a certain name or which is defined in a certain class. * * @param nodeMatcher Which identifiers to look for */ public static Matcher<Tree> hasIdentifier(Matcher<IdentifierTree> nodeMatcher) { return new HasIdentifier(nodeMatcher); } /** Returns true if the Tree node has the expected {@code Modifier}. */ public static <T extends Tree> Matcher<T> hasModifier(Modifier modifier) { return (tree, state) -> { Symbol sym = getSymbol(tree); return sym != null && sym.getModifiers().contains(modifier); }; } /** Matches an AST node which is an expression yielding the indicated static field access. */ public static Matcher<ExpressionTree> staticFieldAccess() { return allOf(isStatic(), isSymbol(VarSymbol.class)); } /** Matches an AST node that is static. */ public static <T extends Tree> Matcher<T> isStatic() { return (tree, state) -> { Symbol sym = getSymbol(tree); return sym != null && sym.isStatic(); }; } /** Matches an AST node that is transient. */ public static <T extends Tree> Matcher<T> isTransient() { return (tree, state) -> getSymbol(tree).getModifiers().contains(Modifier.TRANSIENT); } /** * Matches a {@code throw} statement where the thrown item is matched by the passed {@code * thrownMatcher}. */ public static Matcher<StatementTree> throwStatement( Matcher<? super ExpressionTree> thrownMatcher) { return new Throws(thrownMatcher); } /** * Matches a {@code return} statement where the returned expression is matched by the passed * {@code returnedMatcher}. */ public static Matcher<StatementTree> returnStatement( Matcher<? super ExpressionTree> returnedMatcher) { return new Returns(returnedMatcher); } /** * Matches an {@code assert} statement where the condition is matched by the passed {@code * conditionMatcher}. */ public static Matcher<StatementTree> assertStatement(Matcher<ExpressionTree> conditionMatcher) { return new Asserts(conditionMatcher); } /** Matches a {@code continue} statement. */ public static Matcher<StatementTree> continueStatement() { return (statementTree, state) -> statementTree instanceof ContinueTree; } /** Matches an {@link ExpressionStatementTree} based on its {@link ExpressionTree}. */ public static Matcher<StatementTree> expressionStatement(Matcher<ExpressionTree> matcher) { return (statementTree, state) -> statementTree instanceof ExpressionStatementTree && matcher.matches(((ExpressionStatementTree) statementTree).getExpression(), state); } static Matcher<Tree> isSymbol(java.lang.Class<? extends Symbol> symbolClass) { return new IsSymbol(symbolClass); } /** * Converts the given matcher to one that can be applied to any tree but is only executed when run * on a tree of {@code type} and returns {@code false} for all other tree types. */ public static <S extends T, T extends Tree> Matcher<T> toType( Class<S> type, Matcher<? super S> matcher) { return (tree, state) -> type.isInstance(tree) && matcher.matches(type.cast(tree), state); } /** Matches if this Tree is enclosed by either a synchronized block or a synchronized method. */ public static <T extends Tree> Matcher<T> inSynchronized() { return (tree, state) -> { SynchronizedTree synchronizedTree = ASTHelpers.findEnclosingNode(state.getPath(), SynchronizedTree.class); if (synchronizedTree != null) { return true; } MethodTree methodTree = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class); return methodTree != null && methodTree.getModifiers().getFlags().contains(Modifier.SYNCHRONIZED); }; } /** * Matches if this ExpressionTree refers to the same variable as the one passed into the matcher. */ public static Matcher<ExpressionTree> sameVariable(ExpressionTree expr) { return (tree, state) -> ASTHelpers.sameVariable(tree, expr); } /** Matches if the expression is provably non-null. */ public static Matcher<ExpressionTree> isNonNull() { return new NullnessMatcher(Nullness.NONNULL); } /** Matches if the expression is provably null. */ public static Matcher<ExpressionTree> isNull() { return new NullnessMatcher(Nullness.NULL); } /** * Matches an enhanced for loop if all the given matchers match. * * @param variableMatcher The matcher to apply to the variable. * @param expressionMatcher The matcher to apply to the expression. * @param statementMatcher The matcher to apply to the statement. */ public static Matcher<EnhancedForLoopTree> enhancedForLoop( Matcher<VariableTree> variableMatcher, Matcher<ExpressionTree> expressionMatcher, Matcher<StatementTree> statementMatcher) { return (t, state) -> variableMatcher.matches(t.getVariable(), state) && expressionMatcher.matches(t.getExpression(), state) && statementMatcher.matches(t.getStatement(), state); } /** Matches if the given tree is inside a loop. */ public static <T extends Tree> Matcher<T> inLoop() { return (tree, state) -> { TreePath path = state.getPath().getParentPath(); while (path != null) { Tree node = path.getLeaf(); switch (node.getKind()) { case METHOD: case CLASS: return false; case WHILE_LOOP: case FOR_LOOP: case ENHANCED_FOR_LOOP: case DO_WHILE_LOOP: return true; default: // continue below } path = path.getParentPath(); } return false; }; } /** * Matches an assignment operator AST node if both of the given matchers match. * * @param variableMatcher The matcher to apply to the variable. * @param expressionMatcher The matcher to apply to the expression. */ public static Matcher<AssignmentTree> assignment( Matcher<ExpressionTree> variableMatcher, Matcher<? super ExpressionTree> expressionMatcher) { return (t, state) -> variableMatcher.matches(t.getVariable(), state) && expressionMatcher.matches(t.getExpression(), state); } /** * Matches a type cast AST node if both of the given matchers match. * * @param typeMatcher The matcher to apply to the type. * @param expressionMatcher The matcher to apply to the expression. */ public static Matcher<TypeCastTree> typeCast( Matcher<Tree> typeMatcher, Matcher<ExpressionTree> expressionMatcher) { return (t, state) -> typeMatcher.matches(t.getType(), state) && expressionMatcher.matches(t.getExpression(), state); } /** * Matches an assertion AST node if the given matcher matches its condition. * * @param conditionMatcher The matcher to apply to the condition in the assertion, e.g. in "assert * false", the "false" part of the statement */ public static Matcher<AssertTree> assertionWithCondition( Matcher<ExpressionTree> conditionMatcher) { return (tree, state) -> conditionMatcher.matches(tree.getCondition(), state); } /** * Applies the given matcher recursively to all descendants of an AST node, and matches if any * matching descendant node is found. * * @param treeMatcher The matcher to apply recursively to the tree. */ public static Matcher<Tree> contains(Matcher<Tree> treeMatcher) { return new Contains(treeMatcher); } /** * Applies the given matcher recursively to all descendants of an AST node, and matches if any * matching descendant node is found. * * @param clazz The type of node to be matched. * @param treeMatcher The matcher to apply recursively to the tree. */ public static <T extends Tree, V extends Tree> Matcher<T> contains( Class<V> clazz, Matcher<V> treeMatcher) { final Matcher<Tree> contains = new Contains(toType(clazz, treeMatcher)); return contains::matches; } /** * Matches if the method accepts the given number of arguments. * * @param arity the number of arguments the method should accept */ public static Matcher<MethodTree> methodHasArity(int arity) { return (methodTree, state) -> methodTree.getParameters().size() == arity; } /** * Matches any node that is directly an implementation, but not extension, of the given Class. * * <p>E.x. {@code class C implements I} will match, but {@code class C extends A} will not. * * <p>Additionally, this will only match <i>direct</i> implementations of interfaces. E.g. the * following will not match: * * <p>{@code interface I1 {} interface I2 extends I1 {} class C implements I2 {} ... * isDirectImplementationOf(I1).match(\/*class tree for C*\/); // will not match } */ public static Matcher<ClassTree> isDirectImplementationOf(String clazz) { Matcher<Tree> isProvidedType = isSameType(clazz); return new IsDirectImplementationOf(isProvidedType); } @SafeVarargs public static Matcher<Tree> hasAnyAnnotation(Class<? extends Annotation>... annotations) { ArrayList<Matcher<Tree>> matchers = new ArrayList<>(annotations.length); for (Class<? extends Annotation> annotation : annotations) { matchers.add(hasAnnotation(annotation)); } return anyOf(matchers); } public static Matcher<Tree> hasAnyAnnotation(List<? extends TypeMirror> mirrors) { ArrayList<Matcher<Tree>> matchers = new ArrayList<>(mirrors.size()); for (TypeMirror mirror : mirrors) { matchers.add(hasAnnotation(mirror)); } return anyOf(matchers); } private static final ImmutableSet<Kind> DECLARATION = Sets.immutableEnumSet(Kind.LAMBDA_EXPRESSION, Kind.CLASS, Kind.ENUM, Kind.INTERFACE); public static boolean methodCallInDeclarationOfThrowingRunnable(VisitorState state) { return stream(state.getPath()) // Find the nearest definitional context for this method invocation // (i.e.: the nearest surrounding class or lambda) .filter(t -> DECLARATION.contains(t.getKind())) .findFirst() .map(t -> isThrowingFunctionalInterface(getType(t), state)) .orElseThrow(VerifyException::new); } public static boolean isThrowingFunctionalInterface(Type clazzType, VisitorState state) { return CLASSES_CONSIDERED_THROWING.get(state).stream() .anyMatch(t -> isSubtype(clazzType, t, state)); } /** * {@link FunctionalInterface}s that are generally used as a lambda expression for 'a block of * code that's going to fail', e.g.: * * <p>{@code assertThrows(FooException.class, () -> myCodeThatThrowsAnException()); * errorCollector.checkThrows(FooException.class, () -> myCodeThatThrowsAnException()); } */ // TODO(glorioso): Consider a meta-annotation like @LikelyToThrow instead/in addition? private static final Supplier<ImmutableSet<Type>> CLASSES_CONSIDERED_THROWING = VisitorState.memoize( state -> Stream.of( "org.junit.function.ThrowingRunnable", "org.junit.jupiter.api.function.Executable", "org.assertj.core.api.ThrowableAssert$ThrowingCallable", "com.google.devtools.build.lib.testutil.MoreAsserts$ThrowingRunnable", "com.google.truth.ExpectFailure.AssertionCallback", "com.google.truth.ExpectFailure.DelegatedAssertionCallback", "com.google.truth.ExpectFailure.StandardSubjectBuilderCallback", "com.google.truth.ExpectFailure.SimpleSubjectBuilderCallback") .map(state::getTypeFromString) .filter(Objects::nonNull) .collect(toImmutableSet())); private static class IsDirectImplementationOf extends ChildMultiMatcher<ClassTree, Tree> { public IsDirectImplementationOf(Matcher<Tree> classMatcher) { super(MatchType.AT_LEAST_ONE, classMatcher); } @Override protected Iterable<? extends Tree> getChildNodes(ClassTree classTree, VisitorState state) { return classTree.getImplementsClause(); } } /** Matches an AST node whose compilation unit's package name matches the given pattern. */ public static <T extends Tree> Matcher<T> packageMatches(Pattern pattern) { return (tree, state) -> pattern.matcher(getPackageFullName(state)).matches(); } /** Matches an AST node whose compilation unit starts with this prefix. */ public static <T extends Tree> Matcher<T> packageStartsWith(String prefix) { return (tree, state) -> getPackageFullName(state).startsWith(prefix); } private static String getPackageFullName(VisitorState state) { JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit(); return compilationUnit.packge.fullname.toString(); } private static final Matcher<MethodInvocationTree> STATIC_EQUALS = anyOf( allOf( staticMethod() .onClass("android.support.v4.util.ObjectsCompat") .named("equals") .withParameters("java.lang.Object", "java.lang.Object"), isSameType(BOOLEAN_TYPE)), allOf( staticMethod() .onClass("java.util.Objects") .named("equals") .withParameters("java.lang.Object", "java.lang.Object"), isSameType(BOOLEAN_TYPE)), allOf( staticMethod() .onClass("com.google.common.base.Objects") .named("equal") .withParameters("java.lang.Object", "java.lang.Object"), isSameType(BOOLEAN_TYPE))); /** * Matches an invocation of a recognized static object equality method such as {@link * java.util.Objects#equals}. These are simple facades to {@link Object#equals} that accept null * for either argument. */ public static Matcher<MethodInvocationTree> staticEqualsInvocation() { return STATIC_EQUALS; } private static final Matcher<ExpressionTree> INSTANCE_EQUALS = allOf( instanceMethod().anyClass().named("equals").withParameters("java.lang.Object"), isSameType(BOOLEAN_TYPE)); /** Matches calls to the method {@link Object#equals(Object)} or any override of that method. */ public static Matcher<ExpressionTree> instanceEqualsInvocation() { return INSTANCE_EQUALS; } private static final Matcher<ExpressionTree> ASSERT_EQUALS = staticMethod() .onClassAny("org.junit.Assert", "junit.framework.Assert", "junit.framework.TestCase") .named("assertEquals"); /** * Matches calls to the method {@code org.junit.Assert#assertEquals} and corresponding methods in * JUnit 3.x. */ public static Matcher<ExpressionTree> assertEqualsInvocation() { return ASSERT_EQUALS; } private static final Matcher<ExpressionTree> ASSERT_NOT_EQUALS = staticMethod() .onClassAny("org.junit.Assert", "junit.framework.Assert", "junit.framework.TestCase") .named("assertNotEquals"); /** * Matches calls to the method {@code org.junit.Assert#assertNotEquals} and corresponding methods * in JUnit 3.x. */ public static Matcher<ExpressionTree> assertNotEqualsInvocation() { return ASSERT_NOT_EQUALS; } private static final Matcher<MethodTree> EQUALS_DECLARATION = allOf( methodIsNamed("equals"), methodHasVisibility(Visibility.PUBLIC), methodHasParameters(variableType(isSameType("java.lang.Object"))), anyOf(methodReturns(BOOLEAN_TYPE), methodReturns(JAVA_LANG_BOOLEAN_TYPE))); /** Matches {@link Object#equals} method declaration. */ public static Matcher<MethodTree> equalsMethodDeclaration() { return EQUALS_DECLARATION; } private static final Matcher<MethodTree> TO_STRING_DECLARATION = allOf( methodIsNamed("toString"), methodHasVisibility(Visibility.PUBLIC), methodHasParameters(), methodReturns(STRING_TYPE)); /** Matches {@link Object#toString} method declaration. */ public static Matcher<MethodTree> toStringMethodDeclaration() { return TO_STRING_DECLARATION; } private static final Matcher<MethodTree> HASH_CODE_DECLARATION = allOf( methodIsNamed("hashCode"), methodHasVisibility(Visibility.PUBLIC), methodHasParameters(), methodReturns(INT_TYPE)); /** Matches {@code hashCode} method declaration. */ public static Matcher<MethodTree> hashCodeMethodDeclaration() { return HASH_CODE_DECLARATION; } /** Method signature of serialization methods. */ public static final Matcher<MethodTree> SERIALIZATION_METHODS = allOf( (t, s) -> isSubtype(getSymbol(t).owner.type, s.getSymtab().serializableType, s), anyOf( allOf( methodIsNamed("readObject"), methodHasParameters(isSameType("java.io.ObjectInputStream"))), allOf( methodIsNamed("writeObject"), methodHasParameters(isSameType("java.io.ObjectOutputStream"))), allOf(methodIsNamed("readObjectNoData"), methodReturns(isVoidType())), allOf( methodIsNamed("readResolve"), methodReturns(typeFromString("java.lang.Object"))), allOf( methodIsNamed("writeReplace"), methodReturns(typeFromString("java.lang.Object"))))); public static final Matcher<Tree> IS_INTERFACE = (t, s) -> { Symbol symbol = getSymbol(t); return symbol instanceof ClassSymbol && symbol.isInterface(); }; }
check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
/* * Copyright 2011 The Error Prone 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.google.errorprone.matchers; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getLast; import static com.google.common.collect.Streams.stream; import static com.google.errorprone.suppliers.Suppliers.BOOLEAN_TYPE; import static com.google.errorprone.suppliers.Suppliers.INT_TYPE; import static com.google.errorprone.suppliers.Suppliers.JAVA_LANG_BOOLEAN_TYPE; import static com.google.errorprone.suppliers.Suppliers.STRING_TYPE; import static com.google.errorprone.suppliers.Suppliers.typeFromClass; import static com.google.errorprone.suppliers.Suppliers.typeFromString; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static com.google.errorprone.util.ASTHelpers.stripParentheses; import static java.util.Objects.requireNonNull; import com.google.common.base.VerifyException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.errorprone.VisitorState; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.google.errorprone.matchers.ChildMultiMatcher.MatchType; import com.google.errorprone.matchers.MethodVisibility.Visibility; import com.google.errorprone.matchers.method.MethodMatchers; import com.google.errorprone.matchers.method.MethodMatchers.AnyMethodMatcher; import com.google.errorprone.matchers.method.MethodMatchers.ConstructorMatcher; import com.google.errorprone.matchers.method.MethodMatchers.InstanceMethodMatcher; import com.google.errorprone.matchers.method.MethodMatchers.StaticMethodMatcher; import com.google.errorprone.predicates.TypePredicate; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssertTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ContinueTree; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.SynchronizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.util.Name; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.BiPredicate; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; /** * Static factory methods which make the DSL read more fluently. Since matchers are run in a tight * loop during compilation, performance is important. When assembling a matcher from the DSL, it's * best to construct it only once, by saving the resulting matcher as a static variable for example. * * @author alexeagle@google.com (Alex Eagle) */ public class Matchers { private Matchers() {} /** A matcher that matches any AST node. */ public static <T extends Tree> Matcher<T> anything() { return (t, state) -> true; } /** A matcher that matches no AST node. */ public static <T extends Tree> Matcher<T> nothing() { return (t, state) -> false; } /** Matches an AST node iff it does not match the given matcher. */ public static <T extends Tree> Matcher<T> not(Matcher<T> matcher) { return (t, state) -> !matcher.matches(t, state); } /** * Compose several matchers together, such that the composite matches an AST node iff all the * given matchers do. */ @SafeVarargs public static <T extends Tree> Matcher<T> allOf(final Matcher<? super T>... matchers) { return (t, state) -> { for (Matcher<? super T> matcher : matchers) { if (!matcher.matches(t, state)) { return false; } } return true; }; } /** * Compose several matchers together, such that the composite matches an AST node if any of the * given matchers do. */ public static <T extends Tree> Matcher<T> anyOf( final Iterable<? extends Matcher<? super T>> matchers) { return (t, state) -> { for (Matcher<? super T> matcher : matchers) { if (matcher.matches(t, state)) { return true; } } return false; }; } @SafeVarargs public static <T extends Tree> Matcher<T> anyOf(Matcher<? super T>... matchers) { // IntelliJ claims it can infer <Matcher<? super T>>, but blaze can't (b/132970194). return anyOf(Arrays.<Matcher<? super T>>asList(matchers)); } /** Matches if an AST node is an instance of the given class. */ public static <T extends Tree> Matcher<T> isInstance(java.lang.Class<?> klass) { return (t, state) -> klass.isInstance(t); } /** Matches an AST node of a given kind, for example, an Annotation or a switch block. */ public static <T extends Tree> Matcher<T> kindIs(Kind kind) { return (tree, state) -> tree.getKind() == kind; } /** Matches an AST node of a given kind, for example, an Annotation or a switch block. */ public static <T extends Tree> Matcher<T> kindAnyOf(Set<Kind> kinds) { return (tree, state) -> kinds.contains(tree.getKind()); } /** Matches an AST node which is the same object reference as the given node. */ public static <T extends Tree> Matcher<T> isSame(Tree t) { return (tree, state) -> tree == t; } /** Matches a static method. */ public static StaticMethodMatcher staticMethod() { return MethodMatchers.staticMethod(); } /** Matches an instance method. */ public static InstanceMethodMatcher instanceMethod() { return MethodMatchers.instanceMethod(); } /** Matches a static or instance method. */ public static AnyMethodMatcher anyMethod() { return MethodMatchers.anyMethod(); } /** Matches a constructor. */ public static ConstructorMatcher constructor() { return MethodMatchers.constructor(); } /** * Match a Tree based solely on the Symbol produced by {@link ASTHelpers#getSymbol(Tree)}. * * <p>If {@code getSymbol} returns {@code null}, the matcher returns false instead of calling * {@code pred}. */ public static <T extends Tree> Matcher<T> symbolMatcher(BiPredicate<Symbol, VisitorState> pred) { return (tree, state) -> { Symbol sym = getSymbol(tree); return sym != null && pred.test(sym, state); }; } /** Matches an AST node that represents a non-static field. */ public static Matcher<ExpressionTree> isInstanceField() { return symbolMatcher( (symbol, state) -> symbol.getKind() == ElementKind.FIELD && !symbol.isStatic()); } /** Matches an AST node that represents a local variable or parameter. */ public static Matcher<ExpressionTree> isVariable() { return symbolMatcher( (symbol, state) -> symbol.getKind() == ElementKind.LOCAL_VARIABLE || symbol.getKind() == ElementKind.PARAMETER); } /** * Matches a compound assignment operator AST node which matches a given left-operand matcher, a * given right-operand matcher, and a specific compound assignment operator. * * @param operator Which compound assignment operator to match against. * @param leftOperandMatcher The matcher to apply to the left operand. * @param rightOperandMatcher The matcher to apply to the right operand. */ public static CompoundAssignment compoundAssignment( Kind operator, Matcher<ExpressionTree> leftOperandMatcher, Matcher<ExpressionTree> rightOperandMatcher) { Set<Kind> operators = new HashSet<>(1); operators.add(operator); return new CompoundAssignment(operators, leftOperandMatcher, rightOperandMatcher); } /** * Matches a compound assignment operator AST node which matches a given left-operand matcher, a * given right-operand matcher, and is one of a set of compound assignment operators. Does not * match compound assignment operators. * * @param operators Which compound assignment operators to match against. * @param receiverMatcher The matcher to apply to the receiver. * @param expressionMatcher The matcher to apply to the expression. */ public static CompoundAssignment compoundAssignment( Set<Kind> operators, Matcher<ExpressionTree> receiverMatcher, Matcher<ExpressionTree> expressionMatcher) { return new CompoundAssignment(operators, receiverMatcher, expressionMatcher); } /** * Matches when the receiver of an instance method is the same reference as a particular argument * to the method. For example, receiverSameAsArgument(1) would match {@code obj.method("", obj)} * * @param argNum The number of the argument to compare against (zero-based. */ public static Matcher<? super MethodInvocationTree> receiverSameAsArgument(final int argNum) { return (t, state) -> { List<? extends ExpressionTree> args = t.getArguments(); if (args.size() <= argNum) { return false; } ExpressionTree arg = args.get(argNum); JCExpression methodSelect = (JCExpression) t.getMethodSelect(); if (methodSelect instanceof JCFieldAccess) { JCFieldAccess fieldAccess = (JCFieldAccess) methodSelect; return ASTHelpers.sameVariable(fieldAccess.getExpression(), arg); } else if (methodSelect instanceof JCIdent) { // A bare method call: "equals(foo)". Receiver is implicitly "this". return "this".equals(arg.toString()); } return false; }; } public static Matcher<MethodInvocationTree> receiverOfInvocation( final Matcher<ExpressionTree> expressionTreeMatcher) { return (methodInvocationTree, state) -> { ExpressionTree receiver = ASTHelpers.getReceiver(methodInvocationTree); return receiver != null && expressionTreeMatcher.matches(receiver, state); }; } /** * Matches if the given annotation matcher matches all of or any of the annotations on this tree * node. * * @param matchType Whether to match if the matchers match any of or all of the annotations on * this tree. * @param annotationMatcher The annotation matcher to use. */ public static <T extends Tree> MultiMatcher<T, AnnotationTree> annotations( MatchType matchType, Matcher<AnnotationTree> annotationMatcher) { return new AnnotationMatcher<>(matchType, annotationMatcher); } /** Matches a class in which any of/all of its constructors match the given constructorMatcher. */ public static MultiMatcher<ClassTree, MethodTree> constructor( MatchType matchType, Matcher<MethodTree> constructorMatcher) { return new ConstructorOfClass(matchType, constructorMatcher); } // TODO(cushon): expunge public static Matcher<MethodInvocationTree> methodSelect( Matcher<ExpressionTree> methodSelectMatcher) { return new MethodInvocationMethodSelect(methodSelectMatcher); } public static Matcher<MethodInvocationTree> argument( final int position, final Matcher<ExpressionTree> argumentMatcher) { return new MethodInvocationArgument(position, argumentMatcher); } /** Matches if the given matcher matches all of/any of the arguments to this method invocation. */ public static MultiMatcher<MethodInvocationTree, ExpressionTree> hasArguments( MatchType matchType, Matcher<ExpressionTree> argumentMatcher) { return new HasArguments(matchType, argumentMatcher); } /** * Matches an AST node if it is a method invocation and the given matchers match. * * @param methodSelectMatcher matcher identifying the method being called * @param matchType how to match method arguments with {@code methodArgumentMatcher} * @param methodArgumentMatcher matcher applied to each method argument */ public static Matcher<ExpressionTree> methodInvocation( Matcher<ExpressionTree> methodSelectMatcher, MatchType matchType, Matcher<ExpressionTree> methodArgumentMatcher) { return new MethodInvocation(methodSelectMatcher, matchType, methodArgumentMatcher); } /** * Matches an AST node if it is a method invocation and the method select matches {@code * methodSelectMatcher}. Ignores any arguments. */ public static Matcher<ExpressionTree> methodInvocation( final Matcher<ExpressionTree> methodSelectMatcher) { return (expressionTree, state) -> { if (!(expressionTree instanceof MethodInvocationTree)) { return false; } MethodInvocationTree tree = (MethodInvocationTree) expressionTree; return methodSelectMatcher.matches(tree.getMethodSelect(), state); }; } public static Matcher<MethodInvocationTree> argumentCount(final int argumentCount) { return (t, state) -> t.getArguments().size() == argumentCount; } /** * Matches an AST node if its parent node is matched by the given matcher. For example, {@code * parentNode(kindIs(Kind.RETURN))} would match the {@code this} expression in {@code return * this;} */ public static Matcher<Tree> parentNode(Matcher<Tree> treeMatcher) { return (tree, state) -> { TreePath parent = requireNonNull(state.getPath().getParentPath()); return treeMatcher.matches(parent.getLeaf(), state.withPath(parent)); }; } /** * Matches an AST node if its type is a subtype of the given type. * * @param typeStr a string representation of the type, e.g., "java.util.AbstractList" */ public static <T extends Tree> Matcher<T> isSubtypeOf(String typeStr) { return new IsSubtypeOf<>(typeStr); } /** * Matches an AST node if its type is a subtype of the given type. * * @param type the type to check against */ public static <T extends Tree> Matcher<T> isSubtypeOf(Supplier<Type> type) { return new IsSubtypeOf<>(type); } /** * Matches an AST node if its type is a subtype of the given type. * * @param clazz a class representation of the type, e.g., Action.class. */ public static <T extends Tree> Matcher<T> isSubtypeOf(Class<?> clazz) { return new IsSubtypeOf<>(typeFromClass(clazz)); } /** Matches an AST node if it has the same erased type as the given type. */ public static <T extends Tree> Matcher<T> isSameType(Supplier<Type> type) { return new IsSameType<>(type); } /** Matches an AST node if it has the same erased type as the given type. */ public static <T extends Tree> Matcher<T> isSameType(String typeString) { return new IsSameType<>(typeString); } /** Matches an AST node if it has the same erased type as the given class. */ public static <T extends Tree> Matcher<T> isSameType(Class<?> clazz) { return new IsSameType<>(typeFromClass(clazz)); } /** * Match a Tree based solely on the type produced by {@link ASTHelpers#getType(Tree)}. * * <p>If {@code getType} returns {@code null}, the matcher returns false instead of calling {@code * pred}. */ public static <T extends Tree> Matcher<T> typePredicateMatcher(TypePredicate pred) { return (tree, state) -> { Type type = getType(tree); return type != null && pred.apply(type, state); }; } /** Matches an AST node if its type is an array type. */ public static <T extends Tree> Matcher<T> isArrayType() { return typePredicateMatcher((type, state) -> state.getTypes().isArray(type)); } /** Matches an AST node if its type is a primitive array type. */ public static <T extends Tree> Matcher<T> isPrimitiveArrayType() { return typePredicateMatcher( (type, state) -> state.getTypes().isArray(type) && state.getTypes().elemtype(type).isPrimitive()); } /** Matches an AST node if its type is a primitive type. */ public static <T extends Tree> Matcher<T> isPrimitiveType() { return typePredicateMatcher((type, state) -> type.isPrimitive()); } /** Matches an AST node if its type is either a primitive type or a {@code void} type. */ public static <T extends Tree> Matcher<T> isPrimitiveOrVoidType() { return typePredicateMatcher((type, state) -> type.isPrimitiveOrVoid()); } /** Matches an AST node if its type is a {@code void} type. */ public static <T extends Tree> Matcher<T> isVoidType() { return typePredicateMatcher( (type, state) -> state.getTypes().isSameType(type, state.getSymtab().voidType)); } /** * Matches an AST node if its type is a primitive type, or a boxed version of a primitive type. */ public static <T extends Tree> Matcher<T> isPrimitiveOrBoxedPrimitiveType() { return typePredicateMatcher( (type, state) -> state.getTypes().unboxedTypeOrType(type).isPrimitive()); } /** Matches an AST node if its type is a boxed primitive type. */ public static Matcher<ExpressionTree> isBoxedPrimitiveType() { return typePredicateMatcher( (type, state) -> !state.getTypes().isSameType(state.getTypes().unboxedType(type), Type.noType)); } /** Matches an AST node which is enclosed by a block node that matches the given matcher. */ public static <T extends Tree> Enclosing.Block<T> enclosingBlock(Matcher<BlockTree> matcher) { return new Enclosing.Block<>(matcher); } /** Matches an AST node which is enclosed by a class node that matches the given matcher. */ public static <T extends Tree> Enclosing.Class<T> enclosingClass(Matcher<ClassTree> matcher) { return new Enclosing.Class<>(matcher); } /** Matches an AST node which is enclosed by a method node that matches the given matcher. */ public static <T extends Tree> Enclosing.Method<T> enclosingMethod(Matcher<MethodTree> matcher) { return new Enclosing.Method<>(matcher); } /** * Matches an AST node that is enclosed by some node that matches the given matcher. * * <p>TODO(eaftan): This could be used instead of enclosingBlock and enclosingClass. */ public static Matcher<Tree> enclosingNode(Matcher<Tree> matcher) { return (t, state) -> { TreePath path = state.getPath().getParentPath(); while (path != null) { Tree node = path.getLeaf(); state = state.withPath(path); if (matcher.matches(node, state)) { return true; } path = path.getParentPath(); } return false; }; } private static boolean siblingStatement( int offset, Matcher<StatementTree> matcher, StatementTree statement, VisitorState state) { // TODO(cushon): walking arbitrarily far up to find a block tree often isn't what we want TreePath blockPath = state.findPathToEnclosing(BlockTree.class); if (blockPath == null) { return false; } BlockTree block = (BlockTree) blockPath.getLeaf(); List<? extends StatementTree> statements = block.getStatements(); int idx = statements.indexOf(statement); if (idx == -1) { return false; } idx += offset; if (idx < 0 || idx >= statements.size()) { return false; } StatementTree sibling = statements.get(idx); return matcher.matches(sibling, state.withPath(new TreePath(blockPath, sibling))); } /** * Matches a statement AST node if the following statement in the enclosing block matches the * given matcher. */ public static <T extends StatementTree> Matcher<T> nextStatement(Matcher<StatementTree> matcher) { return (statement, state) -> siblingStatement(/* offset= */ 1, matcher, statement, state); } /** * Matches a statement AST node if the previous statement in the enclosing block matches the given * matcher. */ public static <T extends StatementTree> Matcher<T> previousStatement( Matcher<StatementTree> matcher) { return (statement, state) -> siblingStatement(/* offset= */ -1, matcher, statement, state); } /** Matches a statement AST node if the statement is the last statement in the block. */ public static Matcher<StatementTree> isLastStatementInBlock() { return (statement, state) -> { // TODO(cushon): walking arbitrarily far up to find a block tree often isn't what we want TreePath blockPath = state.findPathToEnclosing(BlockTree.class); if (blockPath == null) { return false; } BlockTree block = (BlockTree) blockPath.getLeaf(); return getLast(block.getStatements()).equals(statement); }; } /** Matches an AST node if it is a literal other than null. */ public static Matcher<ExpressionTree> nonNullLiteral() { return (tree, state) -> { switch (tree.getKind()) { case MEMBER_SELECT: return ((MemberSelectTree) tree).getIdentifier().contentEquals("class"); case INT_LITERAL: case LONG_LITERAL: case FLOAT_LITERAL: case DOUBLE_LITERAL: case BOOLEAN_LITERAL: case CHAR_LITERAL: // fall through case STRING_LITERAL: return true; default: return false; } }; } /** * Matches a Literal AST node if it is a string literal with the given value. For example, {@code * stringLiteral("thing")} matches the literal {@code "thing"} */ public static Matcher<ExpressionTree> stringLiteral(String value) { return new StringLiteral(value); } /** * Matches a Literal AST node if it is a string literal which matches the given {@link Pattern}. * * @see #stringLiteral(String) */ public static Matcher<ExpressionTree> stringLiteral(Pattern pattern) { return new StringLiteral(pattern); } public static Matcher<ExpressionTree> booleanLiteral(boolean value) { return (expressionTree, state) -> expressionTree.getKind() == Kind.BOOLEAN_LITERAL && value == (Boolean) (((LiteralTree) expressionTree).getValue()); } /** * Matches the boolean constant ({@link Boolean#TRUE} or {@link Boolean#FALSE}) corresponding to * the given value. */ public static Matcher<ExpressionTree> booleanConstant(boolean value) { return (expressionTree, state) -> { if (expressionTree instanceof JCFieldAccess) { Symbol symbol = getSymbol(expressionTree); if (symbol.isStatic() && state.getTypes().unboxedTypeOrType(symbol.type).getTag() == TypeTag.BOOLEAN) { if (value) { return symbol.getSimpleName().contentEquals("TRUE"); } else { return symbol.getSimpleName().contentEquals("FALSE"); } } } return false; }; } /** * Ignores any number of parenthesis wrapping an expression and then applies the passed matcher to * that expression. For example, the passed matcher would be applied to {@code value} in {@code * (((value)))}. */ public static Matcher<ExpressionTree> ignoreParens(Matcher<ExpressionTree> innerMatcher) { return (tree, state) -> innerMatcher.matches(stripParentheses(tree), state); } public static Matcher<ExpressionTree> intLiteral(int value) { return (tree, state) -> { return tree.getKind() == Kind.INT_LITERAL && value == ((Integer) ((LiteralTree) tree).getValue()); }; } public static Matcher<ExpressionTree> classLiteral( final Matcher<? super ExpressionTree> classMatcher) { return (tree, state) -> { if (tree.getKind() == Kind.MEMBER_SELECT) { MemberSelectTree select = (MemberSelectTree) tree; return select.getIdentifier().contentEquals("class") && classMatcher.matches(select.getExpression(), state); } return false; }; } /** * Matches an Annotation AST node if the argument to the annotation with the given name has a * value which matches the given matcher. For example, {@code hasArgumentWithValue("value", * stringLiteral("one"))} matches {@code @Thing("one")} or {@code @Thing({"one", "two"})} or * {@code @Thing(value = "one")} */ public static Matcher<AnnotationTree> hasArgumentWithValue( String argumentName, Matcher<ExpressionTree> valueMatcher) { return new AnnotationHasArgumentWithValue(argumentName, valueMatcher); } /** Matches an Annotation AST node if an argument to the annotation does not exist. */ public static Matcher<AnnotationTree> doesNotHaveArgument(String argumentName) { return new AnnotationDoesNotHaveArgument(argumentName); } public static Matcher<AnnotationTree> isType(String annotationClassName) { return new AnnotationType(annotationClassName); } /** * Matches a {@link MethodInvocation} when the arguments at the two given indices are both the * same variable, as determined by {@link ASTHelpers#sameVariable}. * * @param index1 the index of the first actual parameter to test * @param index2 the index of the second actual parameter to test * @throws IndexOutOfBoundsException if the given indices are invalid */ public static Matcher<? super MethodInvocationTree> sameArgument(int index1, int index2) { return (tree, state) -> { List<? extends ExpressionTree> args = tree.getArguments(); return ASTHelpers.sameVariable(args.get(index1), args.get(index2)); }; } /** * Determines whether an expression has an annotation of the given type. This includes annotations * inherited from superclasses due to @Inherited. * * @param annotationClass the binary class name of the annotation (e.g. * "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") */ public static <T extends Tree> Matcher<T> hasAnnotation(String annotationClass) { Supplier<Set<Name>> name = VisitorState.memoize( state -> ImmutableSet.of(state.binaryNameFromClassname(annotationClass))); return (T tree, VisitorState state) -> !ASTHelpers.annotationsAmong(ASTHelpers.getDeclaredSymbol(tree), name.get(state), state) .isEmpty(); } /** * Determines if an expression has an annotation referred to by the given mirror. Accounts for * binary names and annotations inherited due to @Inherited. * * @param annotationMirror mirror referring to the annotation type */ public static Matcher<Tree> hasAnnotation(TypeMirror annotationMirror) { String annotationName = annotationMirror.toString(); return (Tree tree, VisitorState state) -> { JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(state.context); TypeElement typeElem = (TypeElement) javacEnv.getTypeUtils().asElement(annotationMirror); String name; if (typeElem != null) { // Get the binary name if possible ($ to separate nested members). See b/36160747 name = javacEnv.getElementUtils().getBinaryName(typeElem).toString(); } else { name = annotationName; } return ASTHelpers.hasAnnotation(ASTHelpers.getDeclaredSymbol(tree), name, state); }; } /** * Determines whether an expression has an annotation with the given simple name. This does not * include annotations inherited from superclasses due to @Inherited. * * @param simpleName the simple name of the annotation (e.g. "Nullable") */ public static <T extends Tree> Matcher<T> hasAnnotationWithSimpleName(String simpleName) { return (tree, state) -> ASTHelpers.hasDirectAnnotationWithSimpleName( ASTHelpers.getDeclaredSymbol(tree), simpleName); } /** * Determines whether an expression refers to a symbol that has an annotation of the given type. * This includes annotations inherited from superclasses due to @Inherited. * * @param annotationClass the binary class name of the annotation (e.g. * "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") */ public static <T extends Tree> Matcher<T> symbolHasAnnotation(String annotationClass) { return symbolMatcher( (symbol, state) -> ASTHelpers.hasAnnotation(symbol, annotationClass, state)); } /** * Determines whether an expression has an annotation of the given class. This includes * annotations inherited from superclasses due to @Inherited. * * @param inputClass The class of the annotation to look for (e.g, Produces.class). */ public static <T extends Tree> Matcher<T> hasAnnotation(Class<? extends Annotation> inputClass) { return (tree, state) -> ASTHelpers.hasAnnotation(ASTHelpers.getDeclaredSymbol(tree), inputClass, state); } /** * Determines whether an expression refers to a symbol that has an annotation of the given type. * This includes annotations inherited from superclasses due to @Inherited. * * @param inputClass The class of the annotation to look for (e.g, Produces.class). */ public static <T extends Tree> Matcher<T> symbolHasAnnotation( Class<? extends Annotation> inputClass) { return (tree, state) -> ASTHelpers.hasAnnotation(getSymbol(tree), inputClass, state); } /** * Matches if a method or any method it overrides has an annotation of the given type. JUnit 4's * {@code @Test}, {@code @Before}, and {@code @After} annotations behave this way. * * @param annotationClass the binary class name of the annotation (e.g. * "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") */ public static Matcher<MethodTree> hasAnnotationOnAnyOverriddenMethod(String annotationClass) { return (tree, state) -> { MethodSymbol methodSym = getSymbol(tree); if (methodSym == null) { return false; } if (ASTHelpers.hasAnnotation(methodSym, annotationClass, state)) { return true; } for (MethodSymbol method : ASTHelpers.findSuperMethods(methodSym, state.getTypes())) { if (ASTHelpers.hasAnnotation(method, annotationClass, state)) { return true; } } return false; }; } /** Matches a whitelisted method invocation that is known to never return null */ public static Matcher<ExpressionTree> methodReturnsNonNull() { return anyOf( instanceMethod().onDescendantOf("java.lang.Object").named("toString"), instanceMethod().onExactClass("java.lang.String"), staticMethod().onClass("java.lang.String"), instanceMethod().onExactClass("java.util.StringTokenizer").named("nextToken")); } public static Matcher<MethodTree> methodReturns(Matcher<? super Tree> returnTypeMatcher) { return (methodTree, state) -> { Tree returnTree = methodTree.getReturnType(); // Constructors have no return type. return returnTree != null && returnTypeMatcher.matches(returnTree, state); }; } public static Matcher<MethodTree> methodReturns(Supplier<Type> returnType) { return methodReturns(isSameType(returnType)); } /** Match a method that returns a non-primitive type. */ public static Matcher<MethodTree> methodReturnsNonPrimitiveType() { return methodReturns(not(isPrimitiveOrVoidType())); } /** * Match a method declaration with a specific name. * * @param methodName The name of the method to match, e.g., "equals" */ public static Matcher<MethodTree> methodIsNamed(String methodName) { return (methodTree, state) -> methodTree.getName().contentEquals(methodName); } /** * Match a method declaration that starts with a given string. * * @param prefix The prefix. */ public static Matcher<MethodTree> methodNameStartsWith(String prefix) { return (methodTree, state) -> methodTree.getName().toString().startsWith(prefix); } /** * Match a method declaration with a specific enclosing class and method name. * * @param className The fully-qualified name of the enclosing class, e.g. * "com.google.common.base.Preconditions" * @param methodName The name of the method to match, e.g., "checkNotNull" */ public static Matcher<MethodTree> methodWithClassAndName(String className, String methodName) { return (methodTree, state) -> getSymbol(methodTree).getEnclosingElement().getQualifiedName().contentEquals(className) && methodTree.getName().contentEquals(methodName); } /** * Matches an AST node that represents a method declaration, based on the list of * variableMatchers. Applies the variableMatcher at index n to the parameter at index n and * returns true iff they all match. Returns false if the number of variableMatchers provided does * not match the number of parameters. * * <p>If you pass no variableMatchers, this will match methods with no parameters. * * @param variableMatcher an array of matchers to apply to the parameters of the method */ @SafeVarargs public static Matcher<MethodTree> methodHasParameters( final Matcher<VariableTree>... variableMatcher) { return methodHasParameters(ImmutableList.copyOf(variableMatcher)); } /** * Matches an AST node that represents a method declaration, based on the list of * variableMatchers. Applies the variableMatcher at index n to the parameter at index n and * returns true iff they all match. Returns false if the number of variableMatchers provided does * not match the number of parameters. * * <p>If you pass no variableMatchers, this will match methods with no parameters. * * @param variableMatcher a list of matchers to apply to the parameters of the method */ public static Matcher<MethodTree> methodHasParameters( final List<Matcher<VariableTree>> variableMatcher) { return (methodTree, state) -> { if (methodTree.getParameters().size() != variableMatcher.size()) { return false; } int paramIndex = 0; for (Matcher<VariableTree> eachVariableMatcher : variableMatcher) { if (!eachVariableMatcher.matches(methodTree.getParameters().get(paramIndex++), state)) { return false; } } return true; }; } /** Matches if the given matcher matches all of/any of the parameters to this method. */ public static MultiMatcher<MethodTree, VariableTree> methodHasParameters( MatchType matchType, Matcher<VariableTree> parameterMatcher) { return new MethodHasParameters(matchType, parameterMatcher); } public static Matcher<MethodTree> methodHasVisibility(Visibility visibility) { return new MethodVisibility(visibility); } public static Matcher<MethodTree> methodIsConstructor() { return (methodTree, state) -> getSymbol(methodTree).isConstructor(); } /** * Matches a constructor declaration in a specific enclosing class. * * @param className The fully-qualified name of the enclosing class, e.g. * "com.google.common.base.Preconditions" */ public static Matcher<MethodTree> constructorOfClass(String className) { return (methodTree, state) -> { Symbol symbol = getSymbol(methodTree); return symbol.getEnclosingElement().getQualifiedName().contentEquals(className) && symbol.isConstructor(); }; } /** * Matches a class in which at least one method matches the given methodMatcher. * * @param methodMatcher A matcher on MethodTrees to run against all methods in this class. * @return True if some method in the class matches the given methodMatcher. */ public static Matcher<ClassTree> hasMethod(Matcher<MethodTree> methodMatcher) { return (t, state) -> { for (Tree member : t.getMembers()) { if (member instanceof MethodTree && methodMatcher.matches((MethodTree) member, state)) { return true; } } return false; }; } /** * Matches on the type of a VariableTree AST node. * * @param treeMatcher A matcher on the type of the variable. */ public static Matcher<VariableTree> variableType(Matcher<Tree> treeMatcher) { return (variableTree, state) -> treeMatcher.matches(variableTree.getType(), state); } /** * Matches on the initializer of a VariableTree AST node. * * @param expressionTreeMatcher A matcher on the initializer of the variable. */ public static Matcher<VariableTree> variableInitializer( Matcher<ExpressionTree> expressionTreeMatcher) { return (variableTree, state) -> { ExpressionTree initializer = variableTree.getInitializer(); return initializer != null && expressionTreeMatcher.matches(initializer, state); }; } /** * Matches if a {@link VariableTree} is a field declaration, as opposed to a local variable, enum * constant, parameter to a method, etc. */ public static Matcher<VariableTree> isField() { return (variableTree, state) -> ElementKind.FIELD == getSymbol(variableTree).getKind(); } /** * Matches an class based on whether it is nested in another class or method. * * @param kind The kind of nesting to match, eg ANONYMOUS, LOCAL, MEMBER, TOP_LEVEL */ public static Matcher<ClassTree> nestingKind(NestingKind kind) { return (classTree, state) -> kind == getSymbol(classTree).getNestingKind(); } /** * Matches a binary tree if the given matchers match the operands in either order. That is, * returns true if either: matcher1 matches the left operand and matcher2 matches the right * operand or matcher2 matches the left operand and matcher1 matches the right operand */ public static Matcher<BinaryTree> binaryTree( Matcher<ExpressionTree> matcher1, Matcher<ExpressionTree> matcher2) { return (t, state) -> null != ASTHelpers.matchBinaryTree(t, Arrays.asList(matcher1, matcher2), state); } /** * Matches any AST that contains an identifier with a certain property. This matcher can be used, * for instance, to locate identifiers with a certain name or which is defined in a certain class. * * @param nodeMatcher Which identifiers to look for */ public static Matcher<Tree> hasIdentifier(Matcher<IdentifierTree> nodeMatcher) { return new HasIdentifier(nodeMatcher); } /** Returns true if the Tree node has the expected {@code Modifier}. */ public static <T extends Tree> Matcher<T> hasModifier(Modifier modifier) { return (tree, state) -> { Symbol sym = getSymbol(tree); return sym != null && sym.getModifiers().contains(modifier); }; } /** Matches an AST node which is an expression yielding the indicated static field access. */ public static Matcher<ExpressionTree> staticFieldAccess() { return allOf(isStatic(), isSymbol(VarSymbol.class)); } /** Matches an AST node that is static. */ public static <T extends Tree> Matcher<T> isStatic() { return (tree, state) -> { Symbol sym = getSymbol(tree); return sym != null && sym.isStatic(); }; } /** Matches an AST node that is transient. */ public static <T extends Tree> Matcher<T> isTransient() { return (tree, state) -> getSymbol(tree).getModifiers().contains(Modifier.TRANSIENT); } /** * Matches a {@code throw} statement where the thrown item is matched by the passed {@code * thrownMatcher}. */ public static Matcher<StatementTree> throwStatement( Matcher<? super ExpressionTree> thrownMatcher) { return new Throws(thrownMatcher); } /** * Matches a {@code return} statement where the returned expression is matched by the passed * {@code returnedMatcher}. */ public static Matcher<StatementTree> returnStatement( Matcher<? super ExpressionTree> returnedMatcher) { return new Returns(returnedMatcher); } /** * Matches an {@code assert} statement where the condition is matched by the passed {@code * conditionMatcher}. */ public static Matcher<StatementTree> assertStatement(Matcher<ExpressionTree> conditionMatcher) { return new Asserts(conditionMatcher); } /** Matches a {@code continue} statement. */ public static Matcher<StatementTree> continueStatement() { return (statementTree, state) -> statementTree instanceof ContinueTree; } /** Matches an {@link ExpressionStatementTree} based on its {@link ExpressionTree}. */ public static Matcher<StatementTree> expressionStatement(Matcher<ExpressionTree> matcher) { return (statementTree, state) -> statementTree instanceof ExpressionStatementTree && matcher.matches(((ExpressionStatementTree) statementTree).getExpression(), state); } static Matcher<Tree> isSymbol(java.lang.Class<? extends Symbol> symbolClass) { return new IsSymbol(symbolClass); } /** * Converts the given matcher to one that can be applied to any tree but is only executed when run * on a tree of {@code type} and returns {@code false} for all other tree types. */ public static <S extends T, T extends Tree> Matcher<T> toType( Class<S> type, Matcher<? super S> matcher) { return (tree, state) -> type.isInstance(tree) && matcher.matches(type.cast(tree), state); } /** Matches if this Tree is enclosed by either a synchronized block or a synchronized method. */ public static <T extends Tree> Matcher<T> inSynchronized() { return (tree, state) -> { SynchronizedTree synchronizedTree = ASTHelpers.findEnclosingNode(state.getPath(), SynchronizedTree.class); if (synchronizedTree != null) { return true; } MethodTree methodTree = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class); return methodTree != null && methodTree.getModifiers().getFlags().contains(Modifier.SYNCHRONIZED); }; } /** * Matches if this ExpressionTree refers to the same variable as the one passed into the matcher. */ public static Matcher<ExpressionTree> sameVariable(ExpressionTree expr) { return (tree, state) -> ASTHelpers.sameVariable(tree, expr); } /** Matches if the expression is provably non-null. */ public static Matcher<ExpressionTree> isNonNull() { return new NullnessMatcher(Nullness.NONNULL); } /** Matches if the expression is provably null. */ public static Matcher<ExpressionTree> isNull() { return new NullnessMatcher(Nullness.NULL); } /** * Matches an enhanced for loop if all the given matchers match. * * @param variableMatcher The matcher to apply to the variable. * @param expressionMatcher The matcher to apply to the expression. * @param statementMatcher The matcher to apply to the statement. */ public static Matcher<EnhancedForLoopTree> enhancedForLoop( Matcher<VariableTree> variableMatcher, Matcher<ExpressionTree> expressionMatcher, Matcher<StatementTree> statementMatcher) { return (t, state) -> variableMatcher.matches(t.getVariable(), state) && expressionMatcher.matches(t.getExpression(), state) && statementMatcher.matches(t.getStatement(), state); } /** Matches if the given tree is inside a loop. */ public static <T extends Tree> Matcher<T> inLoop() { return (tree, state) -> { TreePath path = state.getPath().getParentPath(); while (path != null) { Tree node = path.getLeaf(); switch (node.getKind()) { case METHOD: case CLASS: return false; case WHILE_LOOP: case FOR_LOOP: case ENHANCED_FOR_LOOP: case DO_WHILE_LOOP: return true; default: // continue below } path = path.getParentPath(); } return false; }; } /** * Matches an assignment operator AST node if both of the given matchers match. * * @param variableMatcher The matcher to apply to the variable. * @param expressionMatcher The matcher to apply to the expression. */ public static Matcher<AssignmentTree> assignment( Matcher<ExpressionTree> variableMatcher, Matcher<? super ExpressionTree> expressionMatcher) { return (t, state) -> variableMatcher.matches(t.getVariable(), state) && expressionMatcher.matches(t.getExpression(), state); } /** * Matches a type cast AST node if both of the given matchers match. * * @param typeMatcher The matcher to apply to the type. * @param expressionMatcher The matcher to apply to the expression. */ public static Matcher<TypeCastTree> typeCast( Matcher<Tree> typeMatcher, Matcher<ExpressionTree> expressionMatcher) { return (t, state) -> typeMatcher.matches(t.getType(), state) && expressionMatcher.matches(t.getExpression(), state); } /** * Matches an assertion AST node if the given matcher matches its condition. * * @param conditionMatcher The matcher to apply to the condition in the assertion, e.g. in "assert * false", the "false" part of the statement */ public static Matcher<AssertTree> assertionWithCondition( Matcher<ExpressionTree> conditionMatcher) { return (tree, state) -> conditionMatcher.matches(tree.getCondition(), state); } /** * Applies the given matcher recursively to all descendants of an AST node, and matches if any * matching descendant node is found. * * @param treeMatcher The matcher to apply recursively to the tree. */ public static Matcher<Tree> contains(Matcher<Tree> treeMatcher) { return new Contains(treeMatcher); } /** * Applies the given matcher recursively to all descendants of an AST node, and matches if any * matching descendant node is found. * * @param clazz The type of node to be matched. * @param treeMatcher The matcher to apply recursively to the tree. */ public static <T extends Tree, V extends Tree> Matcher<T> contains( Class<V> clazz, Matcher<V> treeMatcher) { final Matcher<Tree> contains = new Contains(toType(clazz, treeMatcher)); return contains::matches; } /** * Matches if the method accepts the given number of arguments. * * @param arity the number of arguments the method should accept */ public static Matcher<MethodTree> methodHasArity(int arity) { return (methodTree, state) -> methodTree.getParameters().size() == arity; } /** * Matches any node that is directly an implementation, but not extension, of the given Class. * * <p>E.x. {@code class C implements I} will match, but {@code class C extends A} will not. * * <p>Additionally, this will only match <i>direct</i> implementations of interfaces. E.g. the * following will not match: * * <p>{@code interface I1 {} interface I2 extends I1 {} class C implements I2 {} ... * isDirectImplementationOf(I1).match(\/*class tree for C*\/); // will not match } */ public static Matcher<ClassTree> isDirectImplementationOf(String clazz) { Matcher<Tree> isProvidedType = isSameType(clazz); return new IsDirectImplementationOf(isProvidedType); } @SafeVarargs public static Matcher<Tree> hasAnyAnnotation(Class<? extends Annotation>... annotations) { ArrayList<Matcher<Tree>> matchers = new ArrayList<>(annotations.length); for (Class<? extends Annotation> annotation : annotations) { matchers.add(hasAnnotation(annotation)); } return anyOf(matchers); } public static Matcher<Tree> hasAnyAnnotation(List<? extends TypeMirror> mirrors) { ArrayList<Matcher<Tree>> matchers = new ArrayList<>(mirrors.size()); for (TypeMirror mirror : mirrors) { matchers.add(hasAnnotation(mirror)); } return anyOf(matchers); } private static final ImmutableSet<Kind> DECLARATION = Sets.immutableEnumSet(Kind.LAMBDA_EXPRESSION, Kind.CLASS, Kind.ENUM, Kind.INTERFACE); public static boolean methodCallInDeclarationOfThrowingRunnable(VisitorState state) { return stream(state.getPath()) // Find the nearest definitional context for this method invocation // (i.e.: the nearest surrounding class or lambda) .filter(t -> DECLARATION.contains(t.getKind())) .findFirst() .map(t -> isThrowingFunctionalInterface(getType(t), state)) .orElseThrow(VerifyException::new); } public static boolean isThrowingFunctionalInterface(Type clazzType, VisitorState state) { return CLASSES_CONSIDERED_THROWING.get(state).stream() .anyMatch(t -> isSubtype(clazzType, t, state)); } /** * {@link FunctionalInterface}s that are generally used as a lambda expression for 'a block of * code that's going to fail', e.g.: * * <p>{@code assertThrows(FooException.class, () -> myCodeThatThrowsAnException()); * errorCollector.checkThrows(FooException.class, () -> myCodeThatThrowsAnException()); } */ // TODO(glorioso): Consider a meta-annotation like @LikelyToThrow instead/in addition? private static final Supplier<ImmutableSet<Type>> CLASSES_CONSIDERED_THROWING = VisitorState.memoize( state -> Stream.of( "org.junit.function.ThrowingRunnable", "org.junit.jupiter.api.function.Executable", "org.assertj.core.api.ThrowableAssert$ThrowingCallable", "com.google.devtools.build.lib.testutil.MoreAsserts$ThrowingRunnable", "com.google.truth.ExpectFailure.AssertionCallback", "com.google.truth.ExpectFailure.DelegatedAssertionCallback", "com.google.truth.ExpectFailure.StandardSubjectBuilderCallback", "com.google.truth.ExpectFailure.SimpleSubjectBuilderCallback") .map(state::getTypeFromString) .filter(Objects::nonNull) .collect(toImmutableSet())); private static class IsDirectImplementationOf extends ChildMultiMatcher<ClassTree, Tree> { public IsDirectImplementationOf(Matcher<Tree> classMatcher) { super(MatchType.AT_LEAST_ONE, classMatcher); } @Override protected Iterable<? extends Tree> getChildNodes(ClassTree classTree, VisitorState state) { return classTree.getImplementsClause(); } } /** Matches an AST node whose compilation unit's package name matches the given pattern. */ public static <T extends Tree> Matcher<T> packageMatches(Pattern pattern) { return (tree, state) -> pattern.matcher(getPackageFullName(state)).matches(); } /** Matches an AST node whose compilation unit starts with this prefix. */ public static <T extends Tree> Matcher<T> packageStartsWith(String prefix) { return (tree, state) -> getPackageFullName(state).startsWith(prefix); } private static String getPackageFullName(VisitorState state) { JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit(); return compilationUnit.packge.fullname.toString(); } private static final Matcher<MethodInvocationTree> STATIC_EQUALS = anyOf( allOf( staticMethod() .onClass("android.support.v4.util.ObjectsCompat") .named("equals") .withParameters("java.lang.Object", "java.lang.Object"), isSameType(BOOLEAN_TYPE)), allOf( staticMethod() .onClass("java.util.Objects") .named("equals") .withParameters("java.lang.Object", "java.lang.Object"), isSameType(BOOLEAN_TYPE)), allOf( staticMethod() .onClass("com.google.common.base.Objects") .named("equal") .withParameters("java.lang.Object", "java.lang.Object"), isSameType(BOOLEAN_TYPE))); /** * Matches an invocation of a recognized static object equality method such as {@link * java.util.Objects#equals}. These are simple facades to {@link Object#equals} that accept null * for either argument. */ public static Matcher<MethodInvocationTree> staticEqualsInvocation() { return STATIC_EQUALS; } private static final Matcher<ExpressionTree> INSTANCE_EQUALS = allOf( instanceMethod().anyClass().named("equals").withParameters("java.lang.Object"), isSameType(BOOLEAN_TYPE)); /** Matches calls to the method {@link Object#equals(Object)} or any override of that method. */ public static Matcher<ExpressionTree> instanceEqualsInvocation() { return INSTANCE_EQUALS; } private static final Matcher<ExpressionTree> ASSERT_EQUALS = staticMethod() .onClassAny("org.junit.Assert", "junit.framework.Assert", "junit.framework.TestCase") .named("assertEquals"); /** * Matches calls to the method {@code org.junit.Assert#assertEquals} and corresponding methods in * JUnit 3.x. */ public static Matcher<ExpressionTree> assertEqualsInvocation() { return ASSERT_EQUALS; } private static final Matcher<ExpressionTree> ASSERT_NOT_EQUALS = staticMethod() .onClassAny("org.junit.Assert", "junit.framework.Assert", "junit.framework.TestCase") .named("assertNotEquals"); /** * Matches calls to the method {@code org.junit.Assert#assertNotEquals} and corresponding methods * in JUnit 3.x. */ public static Matcher<ExpressionTree> assertNotEqualsInvocation() { return ASSERT_NOT_EQUALS; } private static final Matcher<MethodTree> EQUALS_DECLARATION = allOf( methodIsNamed("equals"), methodHasVisibility(Visibility.PUBLIC), methodHasParameters(variableType(isSameType("java.lang.Object"))), anyOf(methodReturns(BOOLEAN_TYPE), methodReturns(JAVA_LANG_BOOLEAN_TYPE))); /** Matches {@link Object#equals} method declaration. */ public static Matcher<MethodTree> equalsMethodDeclaration() { return EQUALS_DECLARATION; } private static final Matcher<MethodTree> TO_STRING_DECLARATION = allOf( methodIsNamed("toString"), methodHasVisibility(Visibility.PUBLIC), methodHasParameters(), methodReturns(STRING_TYPE)); /** Matches {@link Object#toString} method declaration. */ public static Matcher<MethodTree> toStringMethodDeclaration() { return TO_STRING_DECLARATION; } private static final Matcher<MethodTree> HASH_CODE_DECLARATION = allOf( methodIsNamed("hashCode"), methodHasVisibility(Visibility.PUBLIC), methodHasParameters(), methodReturns(INT_TYPE)); /** Matches {@code hashCode} method declaration. */ public static Matcher<MethodTree> hashCodeMethodDeclaration() { return HASH_CODE_DECLARATION; } /** Method signature of serialization methods. */ public static final Matcher<MethodTree> SERIALIZATION_METHODS = allOf( (t, s) -> isSubtype(getSymbol(t).owner.type, s.getSymtab().serializableType, s), anyOf( allOf( methodIsNamed("readObject"), methodHasParameters(isSameType("java.io.ObjectInputStream"))), allOf( methodIsNamed("writeObject"), methodHasParameters(isSameType("java.io.ObjectOutputStream"))), allOf(methodIsNamed("readObjectNoData"), methodReturns(isVoidType())), allOf( methodIsNamed("readResolve"), methodReturns(typeFromString("java.lang.Object"))), allOf( methodIsNamed("writeReplace"), methodReturns(typeFromString("java.lang.Object"))))); }
Add a refactoring to remove redundant modifiers. And address other forms of redundancy, in a grab-all check for stuff that isn't significant enough to show in any analyzer. PiperOrigin-RevId: 317851724
check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
Add a refactoring to remove redundant modifiers.
Java
apache-2.0
027117ec0d2d020ac20fbb66142eb86b62b9835b
0
twalthr/flink,sunjincheng121/flink,lincoln-lil/flink,sunjincheng121/flink,tzulitai/flink,StephanEwen/incubator-flink,gyfora/flink,clarkyzl/flink,apache/flink,kl0u/flink,gyfora/flink,lincoln-lil/flink,twalthr/flink,godfreyhe/flink,xccui/flink,kaibozhou/flink,xccui/flink,darionyaphet/flink,greghogan/flink,aljoscha/flink,zhangminglei/flink,mylog00/flink,tillrohrmann/flink,rmetzger/flink,zjureel/flink,rmetzger/flink,kaibozhou/flink,zentol/flink,rmetzger/flink,lincoln-lil/flink,fhueske/flink,wwjiang007/flink,mylog00/flink,xccui/flink,zentol/flink,jinglining/flink,hequn8128/flink,bowenli86/flink,twalthr/flink,tony810430/flink,shaoxuan-wang/flink,aljoscha/flink,shaoxuan-wang/flink,hequn8128/flink,jinglining/flink,mbode/flink,fhueske/flink,tzulitai/flink,lincoln-lil/flink,xccui/flink,jinglining/flink,jinglining/flink,wwjiang007/flink,darionyaphet/flink,bowenli86/flink,darionyaphet/flink,lincoln-lil/flink,zentol/flink,mbode/flink,kl0u/flink,clarkyzl/flink,twalthr/flink,StephanEwen/incubator-flink,yew1eb/flink,godfreyhe/flink,darionyaphet/flink,twalthr/flink,zjureel/flink,sunjincheng121/flink,shaoxuan-wang/flink,zjureel/flink,wwjiang007/flink,godfreyhe/flink,tillrohrmann/flink,xccui/flink,StephanEwen/incubator-flink,shaoxuan-wang/flink,StephanEwen/incubator-flink,shaoxuan-wang/flink,apache/flink,xccui/flink,aljoscha/flink,bowenli86/flink,rmetzger/flink,hequn8128/flink,godfreyhe/flink,GJL/flink,tony810430/flink,hequn8128/flink,shaoxuan-wang/flink,rmetzger/flink,apache/flink,mylog00/flink,kl0u/flink,ueshin/apache-flink,mbode/flink,mylog00/flink,aljoscha/flink,mbode/flink,twalthr/flink,tony810430/flink,kl0u/flink,mylog00/flink,wwjiang007/flink,jinglining/flink,yew1eb/flink,gyfora/flink,apache/flink,fhueske/flink,yew1eb/flink,lincoln-lil/flink,kl0u/flink,hequn8128/flink,ueshin/apache-flink,yew1eb/flink,StephanEwen/incubator-flink,godfreyhe/flink,wwjiang007/flink,zhangminglei/flink,greghogan/flink,tillrohrmann/flink,ueshin/apache-flink,greghogan/flink,darionyaphet/flink,zjureel/flink,bowenli86/flink,tony810430/flink,sunjincheng121/flink,zentol/flink,tzulitai/flink,GJL/flink,tillrohrmann/flink,greghogan/flink,zentol/flink,kaibozhou/flink,fhueske/flink,jinglining/flink,GJL/flink,tzulitai/flink,gyfora/flink,tony810430/flink,fhueske/flink,tony810430/flink,zhangminglei/flink,lincoln-lil/flink,GJL/flink,tony810430/flink,clarkyzl/flink,tzulitai/flink,bowenli86/flink,hequn8128/flink,GJL/flink,zjureel/flink,ueshin/apache-flink,twalthr/flink,gyfora/flink,zjureel/flink,apache/flink,gyfora/flink,ueshin/apache-flink,wwjiang007/flink,apache/flink,apache/flink,wwjiang007/flink,aljoscha/flink,sunjincheng121/flink,aljoscha/flink,zhangminglei/flink,clarkyzl/flink,rmetzger/flink,tillrohrmann/flink,GJL/flink,fhueske/flink,StephanEwen/incubator-flink,rmetzger/flink,clarkyzl/flink,tillrohrmann/flink,zentol/flink,xccui/flink,tzulitai/flink,gyfora/flink,zjureel/flink,greghogan/flink,tillrohrmann/flink,godfreyhe/flink,zhangminglei/flink,mbode/flink,sunjincheng121/flink,bowenli86/flink,kaibozhou/flink,yew1eb/flink,godfreyhe/flink,kl0u/flink,zentol/flink,kaibozhou/flink,kaibozhou/flink,greghogan/flink
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.checkpoint; import org.apache.flink.runtime.jobgraph.JobStatus; import org.apache.flink.runtime.jobmanager.HighAvailabilityMode; import java.util.concurrent.atomic.AtomicLong; /** * {@link CheckpointIDCounter} instances for JobManagers running in {@link HighAvailabilityMode#NONE}. * * <p>Simple wrapper around an {@link AtomicLong}. */ public class StandaloneCheckpointIDCounter implements CheckpointIDCounter { private final AtomicLong checkpointIdCounter = new AtomicLong(1); @Override public void start() throws Exception {} @Override public void shutdown(JobStatus jobStatus) throws Exception {} @Override public long getAndIncrement() throws Exception { return checkpointIdCounter.getAndIncrement(); } @Override public void setCount(long newCount) { checkpointIdCounter.set(newCount); } /** * Returns the last checkpoint ID (current - 1). * * @return Last checkpoint ID. */ public long getLast() { return checkpointIdCounter.get() - 1; } }
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/StandaloneCheckpointIDCounter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.checkpoint; import org.apache.flink.runtime.jobgraph.JobStatus; import org.apache.flink.runtime.jobmanager.HighAvailabilityMode; import java.util.concurrent.atomic.AtomicLong; /** * {@link CheckpointIDCounter} instances for JobManagers running in {@link HighAvailabilityMode#NONE}. * * <p>Simple wrapper around an {@link AtomicLong}. */ public class StandaloneCheckpointIDCounter implements CheckpointIDCounter { private final AtomicLong checkpointIdCounter = new AtomicLong(1); @Override public void start() throws Exception {} @Override public void shutdown(JobStatus jobStatus) throws Exception {} @Override public long getAndIncrement() throws Exception { return checkpointIdCounter.getAndIncrement(); } @Override public void setCount(long newCount) { checkpointIdCounter.set(newCount); } /** * Returns the last checkpoint ID (current - 10. * * @return Last checkpoint ID. */ public long getLast() { return checkpointIdCounter.get() - 1; } }
[hotfix] Correct the javadoc of StandaloneCheckpointIDCounter#getLast This closes #5956.
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/StandaloneCheckpointIDCounter.java
[hotfix] Correct the javadoc of StandaloneCheckpointIDCounter#getLast
Java
apache-2.0
f7f66f2e5c18a614a7d741b5ca3d6a07cb49fd8e
0
spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework
/* * Copyright 2002-2013 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.web.messaging.support; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.SubscribableChannel; import reactor.core.Reactor; import reactor.fn.Consumer; import reactor.fn.Event; import reactor.fn.registry.Registration; import reactor.fn.selector.ObjectSelector; /** * @author Rossen Stoyanchev * @since 4.0 */ public class ReactorMessageChannel implements SubscribableChannel<Message<?>, MessageHandler<Message<?>>> { private static Log logger = LogFactory.getLog(ReactorMessageChannel.class); private final Reactor reactor; private final Object key = new Object(); private String name = toString(); // TODO private final Map<MessageHandler<Message<?>>, Registration<?>> registrations = new HashMap<MessageHandler<Message<?>>, Registration<?>>(); public ReactorMessageChannel(Reactor reactor) { this.reactor = reactor; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } @Override public boolean send(Message<?> message) { return send(message, -1); } @Override public boolean send(Message<?> message, long timeout) { if (logger.isTraceEnabled()) { logger.trace("Channel " + getName() + ", sending message id=" + message.getHeaders().getId()); } this.reactor.notify(this.key, Event.wrap(message)); return true; } @Override public boolean subscribe(final MessageHandler<Message<?>> handler) { if (this.registrations.containsKey(handler)) { logger.warn("Channel " + getName() + ", handler already subscribed " + handler); return false; } if (logger.isTraceEnabled()) { logger.trace("Channel " + getName() + ", subscribing handler " + handler); } Registration<Consumer<Event<Message<?>>>> registration = this.reactor.on( ObjectSelector.objectSelector(key), new MessageHandlerConsumer(handler)); this.registrations.put(handler, registration); return true; } @Override public boolean unsubscribe(MessageHandler<Message<?>> handler) { if (logger.isTraceEnabled()) { logger.trace("Channel " + getName() + ", removing subscription for handler " + handler); } Registration<?> registration = this.registrations.remove(handler); if (registration == null) { if (logger.isTraceEnabled()) { logger.trace("Channel " + getName() + ", no subscription for handler " + handler); } return false; } registration.cancel(); return true; } private static final class MessageHandlerConsumer implements Consumer<Event<Message<?>>> { private final MessageHandler<Message<?>> handler; private MessageHandlerConsumer(MessageHandler<Message<?>> handler) { this.handler = handler; } @Override public void accept(Event<Message<?>> event) { Message<?> message = event.getData(); try { this.handler.handleMessage(message); } catch (Throwable t) { // TODO logger.error("Failed to process message " + message, t); } } } }
spring-websocket/src/main/java/org/springframework/web/messaging/support/ReactorMessageChannel.java
/* * Copyright 2002-2013 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.web.messaging.support; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.SubscribableChannel; import reactor.core.Reactor; import reactor.fn.Consumer; import reactor.fn.Event; import reactor.fn.registry.Registration; import reactor.fn.selector.ObjectSelector; /** * @author Rossen Stoyanchev * @since 4.0 */ public class ReactorMessageChannel implements SubscribableChannel<Message<?>, MessageHandler<Message<?>>> { private static Log logger = LogFactory.getLog(ReactorMessageChannel.class); private final Reactor reactor; private final Object key = new Object(); private String name = toString(); // TODO private final Map<MessageHandler<Message<?>>, Registration<?>> registrations = new HashMap<MessageHandler<Message<?>>, Registration<?>>(); public ReactorMessageChannel(Reactor reactor) { this.reactor = reactor; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } @Override public boolean send(Message<?> message) { return send(message, -1); } @Override public boolean send(Message<?> message, long timeout) { if (logger.isTraceEnabled()) { logger.trace("Channel " + getName() + ", sending message id=" + message.getHeaders().getId()); } this.reactor.notify(this.key, Event.wrap(message)); return true; } @Override public boolean subscribe(final MessageHandler<Message<?>> handler) { if (this.registrations.containsKey(handler)) { logger.warn("Channel " + getName() + ", handler already subscribed " + handler); return false; } if (logger.isTraceEnabled()) { logger.trace("Channel " + getName() + ", subscribing handler " + handler); } Registration<Consumer<Event<Message<?>>>> registration = this.reactor.on( ObjectSelector.objectSelector(key), new MessageHandlerConsumer(handler)); this.registrations.put(handler, registration); return true; } @Override public boolean unsubscribe(MessageHandler<Message<?>> handler) { if (logger.isTraceEnabled()) { logger.trace("Channel " + getName() + ", removing subscription for handler " + handler); } Registration<?> registration = this.registrations.get(handler); if (registration == null) { if (logger.isTraceEnabled()) { logger.trace("Channel " + getName() + ", no subscription for handler " + handler); } return false; } registration.cancel(); return true; } private static final class MessageHandlerConsumer implements Consumer<Event<Message<?>>> { private final MessageHandler<Message<?>> handler; private MessageHandlerConsumer(MessageHandler<Message<?>> handler) { this.handler = handler; } @Override public void accept(Event<Message<?>> event) { Message<?> message = event.getData(); try { this.handler.handleMessage(message); } catch (Throwable t) { // TODO logger.error("Failed to process message " + message, t); } } } }
Fix minor issue in ReactorMessageChannel
spring-websocket/src/main/java/org/springframework/web/messaging/support/ReactorMessageChannel.java
Fix minor issue in ReactorMessageChannel
Java
apache-2.0
94473100167edc330767e2de956d685ce45ad7d1
0
vitlroth/treinamento,vitlroth/treinamento,vitlroth/treinamento,vitlroth/treinamento
package bean; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.lang.Object; import dao.ProdutoDao; import util.Relatorio; public class ProdutoBean { private Integer idproduto; private String nome; private String datacotacao; private String unidade; private String empAux; private Double valor; private EmpresaBean emp; private String numeroDeRegistros; private String sequenciaRegistros; public int cont; public void setEmpAux(String empAux) { this.empAux = empAux; } public String getEmpAux() { return empAux; } public String getSequenciaRegistros() { return sequenciaRegistros; } public void setSequenciaRegistros(String sequenciaRegistros) { this.sequenciaRegistros = sequenciaRegistros; } public String getNumeroDeRegistros() { return numeroDeRegistros; } public void setNumeroDeRegistros(String numeroDeRegistros) { this.numeroDeRegistros = numeroDeRegistros; } public EmpresaBean getEmp() { return emp; } public void setEmp(EmpresaBean emp) { this.emp = emp; } public Integer getIdproduto() { return idproduto; } public void setIdproduto(Integer idproduto) { this.idproduto = idproduto; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDatacotacao() { return datacotacao; } public void setDatacotacao(String datacotacao) { this.datacotacao = datacotacao; } public String getUnidade() { return unidade; } public void setUnidade(String unidade) { this.unidade = unidade; } public Double getValor() { return valor; } public void setValor(Double valor) { this.valor = valor; } /** * Mtodo responsavel de gerar Relatrio apartir de uma lista * @param request * @param response */ public void gerarRelatorioPdf(HttpServletRequest request, HttpServletResponse response) { // caminho do relatrio InputStream relatorio; try { HttpSession sessao = request.getSession(); relatorio = sessao.getServletContext().getResourceAsStream("relatorios/relatorio.jasper"); HashMap<String, Object> hs = new HashMap<>(); Calendar r = Calendar.getInstance(); hs.put("Data", r.getTime()); ProdutoDao dao = new ProdutoDao(); ArrayList<ProdutoBean> lista; lista = dao.getlistar(); Relatorio.gerarPDF(relatorio, hs, lista, response); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block System.out.println("Arquivo no foi encontrado:"); }catch (Exception e){ e.printStackTrace(); System.out.println("Erro ao gerar relatorio PDF produtoBean"); } } public ArrayList<ProdutoBean> lista(HttpServletRequest request) { ArrayList<ProdutoBean> l = null; ProdutoDao dao = new ProdutoDao(); try { l = dao.getlistar(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return l; } public ArrayList<ProdutoBean> listaPaginacao(int numReg, int numPag) { ArrayList<ProdutoBean> l = null; ProdutoDao dao = new ProdutoDao(); try { String numR = String.valueOf(numReg); String numP = String.valueOf(numPag); l = dao.getListarPag(numR, numP); return l; } catch (Exception e) { e.printStackTrace(); } return l; } }
src/bean/ProdutoBean.java
package bean; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.ProdutoDao; import dao.UsuarioDao; import util.Relatorio; public class ProdutoBean { private Integer idproduto; private String nome; private String datacotacao; private String unidade; private String empAux; private Double valor; private EmpresaBean emp; private String numeroDeRegistros; private String sequenciaRegistros; public int cont; public void setEmpAux(String empAux) { this.empAux = empAux; } public String getEmpAux() { return empAux; } public String getSequenciaRegistros() { return sequenciaRegistros; } public void setSequenciaRegistros(String sequenciaRegistros) { this.sequenciaRegistros = sequenciaRegistros; } public String getNumeroDeRegistros() { return numeroDeRegistros; } public void setNumeroDeRegistros(String numeroDeRegistros) { this.numeroDeRegistros = numeroDeRegistros; } public EmpresaBean getEmp() { return emp; } public void setEmp(EmpresaBean emp) { this.emp = emp; } public Integer getIdproduto() { return idproduto; } public void setIdproduto(Integer idproduto) { this.idproduto = idproduto; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDatacotacao() { return datacotacao; } public void setDatacotacao(String datacotacao) { this.datacotacao = datacotacao; } public String getUnidade() { return unidade; } public void setUnidade(String unidade) { this.unidade = unidade; } public Double getValor() { return valor; } public void setValor(Double valor) { this.valor = valor; } /** * Mtodo responsavel de gerar Relatrio apartir de uma lista * @param request * @param response */ public void gerarRelatorioPdf(HttpServletRequest request, HttpServletResponse response) { // caminho do relatrio String path = "C:\\Users\\vitlr\\workspace\\treinamento\\WebContent\\relatorios\\rel_produtos.jasper"; HashMap<String, Object> hs = new HashMap<>(); Calendar r = Calendar.getInstance(); hs.put("Data", r.getTime()); ProdutoDao dao = new ProdutoDao(); ArrayList<ProdutoBean> lista; try { lista = dao.getlistar(); Relatorio.gerarPDF(path, hs, lista, response); } catch (Exception e) { e.printStackTrace(); System.out.println("Erro ao gerar relatorio PDF produtoBean"); } } public ArrayList<ProdutoBean> lista(HttpServletRequest request) { ArrayList<ProdutoBean> l = null; ProdutoDao dao = new ProdutoDao(); try { l = dao.getlistar(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return l; } public ArrayList<ProdutoBean> listaPaginacao(int numReg, int numPag) { ArrayList<ProdutoBean> l = null; ProdutoDao dao = new ProdutoDao(); try { String numR = String.valueOf(numReg); String numP = String.valueOf(numPag); l = dao.getListarPag(numR, numP); return l; } catch (Exception e) { e.printStackTrace(); } return l; } }
* Incluido método gerarRelatorioPdf
src/bean/ProdutoBean.java
* Incluido método gerarRelatorioPdf
Java
apache-2.0
a21f92dab17495a300f3fa34d158863a8570e141
0
clumsy/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,semonte/intellij-community,jagguli/intellij-community,signed/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,allotria/intellij-community,FHannes/intellij-community,signed/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,kdwink/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,semonte/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,semonte/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,amith01994/intellij-community,allotria/intellij-community,samthor/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,samthor/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,retomerz/intellij-community,fitermay/intellij-community,hurricup/intellij-community,clumsy/intellij-community,jagguli/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,blademainer/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,allotria/intellij-community,FHannes/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,semonte/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,supersven/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,caot/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,supersven/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,slisson/intellij-community,kool79/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,holmes/intellij-community,nicolargo/intellij-community,da1z/intellij-community,orekyuu/intellij-community,samthor/intellij-community,wreckJ/intellij-community,signed/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,signed/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,slisson/intellij-community,ibinti/intellij-community,samthor/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ryano144/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,holmes/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,dslomov/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,dslomov/intellij-community,dslomov/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,retomerz/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,amith01994/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,signed/intellij-community,vladmm/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,Distrotech/intellij-community,kool79/intellij-community,ryano144/intellij-community,FHannes/intellij-community,samthor/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,signed/intellij-community,fitermay/intellij-community,diorcety/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,vladmm/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,xfournet/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,supersven/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,caot/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,fnouama/intellij-community,holmes/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,vladmm/intellij-community,kdwink/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,allotria/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,caot/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,izonder/intellij-community,ryano144/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,izonder/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,samthor/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,supersven/intellij-community,kdwink/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,allotria/intellij-community,izonder/intellij-community,xfournet/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,slisson/intellij-community,xfournet/intellij-community,caot/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,allotria/intellij-community,holmes/intellij-community,slisson/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,wreckJ/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,supersven/intellij-community,da1z/intellij-community,vvv1559/intellij-community,kool79/intellij-community,allotria/intellij-community,xfournet/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,slisson/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,allotria/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,hurricup/intellij-community,retomerz/intellij-community,asedunov/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,holmes/intellij-community,dslomov/intellij-community,supersven/intellij-community,slisson/intellij-community,adedayo/intellij-community,signed/intellij-community,xfournet/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,asedunov/intellij-community,kdwink/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,asedunov/intellij-community,kool79/intellij-community,samthor/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,semonte/intellij-community,caot/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,petteyg/intellij-community,jagguli/intellij-community,da1z/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,caot/intellij-community,clumsy/intellij-community,petteyg/intellij-community,dslomov/intellij-community,dslomov/intellij-community,vladmm/intellij-community,amith01994/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,xfournet/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,clumsy/intellij-community,da1z/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,retomerz/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,hurricup/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,kool79/intellij-community,fnouama/intellij-community,apixandru/intellij-community,izonder/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,semonte/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,signed/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,adedayo/intellij-community,jagguli/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,signed/intellij-community,slisson/intellij-community,diorcety/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,diorcety/intellij-community,retomerz/intellij-community,hurricup/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,allotria/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,slisson/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,semonte/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,retomerz/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,kdwink/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,kool79/intellij-community,izonder/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,caot/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,signed/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,jagguli/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,adedayo/intellij-community,caot/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,blademainer/intellij-community,da1z/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,robovm/robovm-studio,fnouama/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,holmes/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,caot/intellij-community,allotria/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,ibinti/intellij-community,signed/intellij-community,asedunov/intellij-community,da1z/intellij-community,izonder/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,caot/intellij-community
/* * 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.openapi.components.impl.stores; import com.intellij.openapi.components.*; import com.intellij.openapi.components.StateStorage.SaveSession; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.project.impl.ProjectManagerImpl; import com.intellij.openapi.util.Couple; import com.intellij.util.containers.ContainerUtil; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; public class DefaultProjectStoreImpl extends ProjectStoreImpl { private final ProjectManagerImpl myProjectManager; @NonNls private static final String ROOT_TAG_NAME = "defaultProject"; public DefaultProjectStoreImpl(@NotNull ProjectImpl project, @NotNull ProjectManagerImpl projectManager, @NotNull PathMacroManager pathMacroManager) { super(project, pathMacroManager); myProjectManager = projectManager; } @Nullable Element getStateCopy() { final Element element = myProjectManager.getDefaultProjectRootElement(); return element != null ? element.clone() : null; } @NotNull @Override protected StateStorageManager createStateStorageManager() { final XmlElementStorage storage = new XmlElementStorage("", RoamingType.DISABLED, myPathMacroManager.createTrackingSubstitutor(), ROOT_TAG_NAME, null) { @Override @Nullable protected Element loadLocalData() { return getStateCopy(); } @Override protected XmlElementStorageSaveSession createSaveSession(@NotNull StorageData storageData) { return new XmlElementStorageSaveSession(storageData) { @Override protected void doSave(@Nullable Element element) { // we must set empty element instead of null as indicator - ProjectManager state is ready to save myProjectManager.setDefaultProjectRootElement(element == null ? new Element("empty") : element); } // we must not collapse paths here, because our solution is just a big hack // by default, getElementToSave() returns collapsed paths -> setDefaultProjectRootElement -> project manager writeExternal -> save -> compare old and new - diff because old has expanded, but new collapsed // -> needless save @Override protected boolean isCollapsePathsOnSave() { return false; } }; } @Override @NotNull protected StorageData createStorageData() { return new BaseStorageData(ROOT_TAG_NAME); } }; //noinspection deprecation return new StateStorageManager() { @Override public void addMacro(@NotNull String macro, @NotNull String expansion) { throw new UnsupportedOperationException("Method addMacro not implemented in " + getClass()); } @Override @Nullable public TrackingPathMacroSubstitutor getMacroSubstitutor() { return null; } @Override @Nullable public StateStorage getStateStorage(@NotNull Storage storageSpec) throws StateStorageException { return storage; } @Nullable @Override public StateStorage getStateStorage(@NotNull String fileSpec, @NotNull RoamingType roamingType) { return storage; } @NotNull @Override public Couple<Collection<FileBasedStorage>> getCachedFileStateStorages(@NotNull Collection<String> changed, @NotNull Collection<String> deleted) { return new Couple<Collection<FileBasedStorage>>(Collections.<FileBasedStorage>emptyList(), Collections.<FileBasedStorage>emptyList()); } @Override public void clearStateStorage(@NotNull String file) { } @Nullable @Override public ExternalizationSession startExternalization() { StateStorage.ExternalizationSession externalizationSession = storage.startExternalization(); return externalizationSession == null ? null : new MyExternalizationSession(externalizationSession); } @NotNull @Override public String expandMacros(@NotNull String file) { throw new UnsupportedOperationException("Method expandMacros not implemented in " + getClass()); } @NotNull @Override public String collapseMacros(@NotNull String path) { throw new UnsupportedOperationException("Method collapseMacros not implemented in " + getClass()); } @Override @Nullable public StateStorage getOldStorage(@NotNull Object component, @NotNull String componentName, @NotNull StateStorageOperation operation) { return storage; } @Override public void setStreamProvider(@Nullable StreamProvider streamProvider) { throw new UnsupportedOperationException("Method setStreamProvider not implemented in " + getClass()); } @Nullable @Override public StreamProvider getStreamProvider() { throw new UnsupportedOperationException("Method getStreamProviders not implemented in " + getClass()); } @NotNull @Override public Collection<String> getStorageFileNames() { throw new UnsupportedOperationException("Method getStorageFileNames not implemented in " + getClass()); } }; } @Override public void load() throws IOException { if (myProjectManager.getDefaultProjectRootElement() != null) { super.load(); } } private static class MyExternalizationSession implements StateStorageManager.ExternalizationSession { @NotNull final StateStorage.ExternalizationSession externalizationSession; public MyExternalizationSession(@NotNull StateStorage.ExternalizationSession externalizationSession) { this.externalizationSession = externalizationSession; } @Override public void setState(@NotNull Storage[] storageSpecs, @NotNull Object component, @NotNull String componentName, @NotNull Object state) { externalizationSession.setState(component, componentName, state, null); } @Override public void setStateInOldStorage(@NotNull Object component, @NotNull String componentName, @NotNull Object state) { externalizationSession.setState(component, componentName, state, null); } @NotNull @Override public List<SaveSession> createSaveSessions() { return ContainerUtil.createMaybeSingletonList(externalizationSession.createSaveSession()); } } }
platform/platform-impl/src/com/intellij/openapi/components/impl/stores/DefaultProjectStoreImpl.java
/* * 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.openapi.components.impl.stores; import com.intellij.openapi.components.*; import com.intellij.openapi.components.StateStorage.SaveSession; import com.intellij.openapi.project.impl.ProjectImpl; import com.intellij.openapi.project.impl.ProjectManagerImpl; import com.intellij.openapi.util.Couple; import com.intellij.util.containers.ContainerUtil; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; public class DefaultProjectStoreImpl extends ProjectStoreImpl { private final ProjectManagerImpl myProjectManager; @NonNls private static final String ROOT_TAG_NAME = "defaultProject"; public DefaultProjectStoreImpl(@NotNull ProjectImpl project, @NotNull ProjectManagerImpl projectManager, @NotNull PathMacroManager pathMacroManager) { super(project, pathMacroManager); myProjectManager = projectManager; } @Nullable Element getStateCopy() { final Element element = myProjectManager.getDefaultProjectRootElement(); return element != null ? element.clone() : null; } @NotNull @Override protected StateStorageManager createStateStorageManager() { final XmlElementStorage storage = new XmlElementStorage("", RoamingType.DISABLED, myPathMacroManager.createTrackingSubstitutor(), ROOT_TAG_NAME, null) { @Override @Nullable protected Element loadLocalData() { return myProjectManager.getDefaultProjectRootElement(); } @Override protected XmlElementStorageSaveSession createSaveSession(@NotNull StorageData storageData) { return new XmlElementStorageSaveSession(storageData) { @Override protected void doSave(@Nullable Element element) { // we must set empty element instead of null as indicator - ProjectManager state is ready to save myProjectManager.setDefaultProjectRootElement(element == null ? new Element("empty") : element); } // we must not collapse paths here, because our solution is just a big hack // by default, getElementToSave() returns collapsed paths -> setDefaultProjectRootElement -> project manager writeExternal -> save -> compare old and new - diff because old has expanded, but new collapsed // -> needless save @Override protected boolean isCollapsePathsOnSave() { return false; } }; } @Override @NotNull protected StorageData createStorageData() { return new BaseStorageData(ROOT_TAG_NAME); } }; //noinspection deprecation return new StateStorageManager() { @Override public void addMacro(@NotNull String macro, @NotNull String expansion) { throw new UnsupportedOperationException("Method addMacro not implemented in " + getClass()); } @Override @Nullable public TrackingPathMacroSubstitutor getMacroSubstitutor() { return null; } @Override @Nullable public StateStorage getStateStorage(@NotNull Storage storageSpec) throws StateStorageException { return storage; } @Nullable @Override public StateStorage getStateStorage(@NotNull String fileSpec, @NotNull RoamingType roamingType) { return storage; } @NotNull @Override public Couple<Collection<FileBasedStorage>> getCachedFileStateStorages(@NotNull Collection<String> changed, @NotNull Collection<String> deleted) { return new Couple<Collection<FileBasedStorage>>(Collections.<FileBasedStorage>emptyList(), Collections.<FileBasedStorage>emptyList()); } @Override public void clearStateStorage(@NotNull String file) { } @Nullable @Override public ExternalizationSession startExternalization() { StateStorage.ExternalizationSession externalizationSession = storage.startExternalization(); return externalizationSession == null ? null : new MyExternalizationSession(externalizationSession); } @NotNull @Override public String expandMacros(@NotNull String file) { throw new UnsupportedOperationException("Method expandMacros not implemented in " + getClass()); } @NotNull @Override public String collapseMacros(@NotNull String path) { throw new UnsupportedOperationException("Method collapseMacros not implemented in " + getClass()); } @Override @Nullable public StateStorage getOldStorage(@NotNull Object component, @NotNull String componentName, @NotNull StateStorageOperation operation) { return storage; } @Override public void setStreamProvider(@Nullable StreamProvider streamProvider) { throw new UnsupportedOperationException("Method setStreamProvider not implemented in " + getClass()); } @Nullable @Override public StreamProvider getStreamProvider() { throw new UnsupportedOperationException("Method getStreamProviders not implemented in " + getClass()); } @NotNull @Override public Collection<String> getStorageFileNames() { throw new UnsupportedOperationException("Method getStorageFileNames not implemented in " + getClass()); } }; } @Override public void load() throws IOException { if (myProjectManager.getDefaultProjectRootElement() != null) { super.load(); } } private static class MyExternalizationSession implements StateStorageManager.ExternalizationSession { @NotNull final StateStorage.ExternalizationSession externalizationSession; public MyExternalizationSession(@NotNull StateStorage.ExternalizationSession externalizationSession) { this.externalizationSession = externalizationSession; } @Override public void setState(@NotNull Storage[] storageSpecs, @NotNull Object component, @NotNull String componentName, @NotNull Object state) { externalizationSession.setState(component, componentName, state, null); } @Override public void setStateInOldStorage(@NotNull Object component, @NotNull String componentName, @NotNull Object state) { externalizationSession.setState(component, componentName, state, null); } @NotNull @Override public List<SaveSession> createSaveSessions() { return ContainerUtil.createMaybeSingletonList(externalizationSession.createSaveSession()); } } }
we remove elements from locally loaded element — DefaultProjectStoreImpl is hack, so, this correct behaviour leads to IDEA-134505 Default settings are not applied anymore. We must clone element.
platform/platform-impl/src/com/intellij/openapi/components/impl/stores/DefaultProjectStoreImpl.java
we remove elements from locally loaded element — DefaultProjectStoreImpl is hack, so, this correct behaviour leads to IDEA-134505 Default settings are not applied anymore. We must clone element.
Java
apache-2.0
cc9d61f94b1a42ab49da3ecc4ce0db7840bec0f2
0
stackforge/monasca-api,sapcc/monasca-api,stackforge/monasca-api,stackforge/monasca-api,openstack/monasca-api,openstack/monasca-api,sapcc/monasca-api,sapcc/monasca-api,stackforge/monasca-api,openstack/monasca-api
/* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * 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 monasca.api.infrastructure.persistence.vertica; import monasca.api.domain.model.metric.MetricDefinitionRepo; import monasca.api.domain.model.metric.MetricName; import monasca.api.infrastructure.persistence.DimensionQueries; import monasca.api.resource.exception.Exceptions; import monasca.common.model.metric.MetricDefinition; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.joda.time.DateTime; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.Query; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; public class MetricDefinitionVerticaRepoImpl implements MetricDefinitionRepo { private static final Logger logger = LoggerFactory.getLogger(MetricDefinitionVerticaRepoImpl.class); private static final String FIND_METRIC_DEFS_SQL = "SELECT defDims.id as defDimsId, def.name, dims.name as dName, dims.value AS dValue " + "FROM MonMetrics.Definitions def, MonMetrics.DefinitionDimensions defDims " // Outer join needed in case there are no dimensions for a definition. + "LEFT OUTER JOIN MonMetrics.Dimensions dims ON dims.dimension_set_id = defDims" + ".dimension_set_id " + "WHERE def.id = defDims.definition_id " + "AND defDims.id IN (%s) " + "ORDER BY defDims.id ASC "; private static final String METRIC_DEFINITIONS_SUB_SELECT = "SELECT defDimsSub.id " + "FROM MonMetrics.Definitions defSub, MonMetrics.DefinitionDimensions defDimsSub" + "%s " // Dimensions inner join goes here if dimensions specified. + "WHERE defDimsSub.definition_id = defSub.id " + "AND defSub.tenant_id = :tenantId " + "%s " // Name goes here. + "%s " // Offset goes here. + "%s " // Optional timestamp qualifier goes here + "ORDER BY defdimsSub.id ASC %s"; // Limit goes here. private static final String FIND_METRIC_NAMES_SQL = "SELECT distinct def.id, def.name " + "FROM MonMetrics.Definitions def " + "WHERE def.id IN (%s) " // Subselect goes here + "ORDER BY def.id ASC "; private static final String METRIC_NAMES_SUB_SELECT = "SELECT distinct MAX(defSub.id) as max_id " // The aggregation function gives us one id per name + "FROM MonMetrics.Definitions defSub, MonMetrics.DefinitionDimensions defDimsSub" + "%s " // Dimensions inner join goes here if dimensions specified. + "WHERE defDimsSub.definition_id = defSub.id " + "AND defSub.tenant_id = :tenantId " + "%s " // Offset goes here. + "GROUP BY defSub.name " // This is to reduce the (id, name) sets to only include unique names + "ORDER BY max_id ASC %s"; // Limit goes here. private static final String DEFDIM_IDS_SELECT = "SELECT defDims.id " + "FROM MonMetrics.Definitions def, MonMetrics.DefinitionDimensions defDims " + "WHERE defDims.definition_id = def.id " + "AND def.tenant_id = :tenantId " + "%s " // Name and clause here + "%s;"; // Dimensions and clause goes here private static final String MEASUREMENT_AND_CLAUSE = "AND defDims.id IN (" + "SELECT definition_dimensions_id FROM " + "MonMetrics.Measurements " + "WHERE to_hex(definition_dimensions_id) " + "%s " // List of definition dimension ids here + "%s ) "; // start or start and end time here private static final String TABLE_TO_JOIN_DIMENSIONS_ON = "defDimsSub"; private final DBI db; @Inject public MetricDefinitionVerticaRepoImpl(@Named("vertica") DBI db) { this.db = db; } @Override public List<MetricName> findNames( String tenantId, Map<String, String> dimensions, String offset, int limit) throws Exception { List<Map<String, Object>> rows = executeMetricNamesQuery(tenantId, dimensions, offset, limit); List<MetricName> metricNameList = new ArrayList<>(rows.size()); for (Map<String, Object> row : rows) { byte[] defId = (byte[]) row.get("id"); String name = (String) row.get("name"); MetricName metricName = new MetricName(Hex.encodeHexString(defId), name); metricNameList.add(metricName); } return metricNameList; } private List<Map<String, Object>> executeMetricNamesQuery( String tenantId, Map<String, String> dimensions, String offset, int limit) { String offsetPart = ""; if (offset != null && !offset.isEmpty()) { offsetPart = " and defSub.id > :offset "; } // Can't bind limit in a nested sub query. So, just tack on as String. String limitPart = " limit " + Integer.toString(limit + 1); String defSubSelect = String.format(METRIC_NAMES_SUB_SELECT, MetricQueries.buildJoinClauseFor(dimensions, TABLE_TO_JOIN_DIMENSIONS_ON), offsetPart, limitPart); String sql = String.format(FIND_METRIC_NAMES_SQL, defSubSelect); try (Handle h = db.open()) { Query<Map<String, Object>> query = h.createQuery(sql).bind("tenantId", tenantId); if (offset != null && !offset.isEmpty()) { logger.debug("binding offset: {}", offset); try { query.bind("offset", Hex.decodeHex(offset.toCharArray())); } catch (DecoderException e) { throw Exceptions.badRequest("failed to decode offset " + offset, e); } } DimensionQueries.bindDimensionsToQuery(query, dimensions); return query.list(); } } @Override public List<MetricDefinition> find( String tenantId, String name, Map<String, String> dimensions, DateTime startTime, DateTime endTime, String offset, int limit) { List<Map<String, Object>> rows = executeMetricDefsQuery(tenantId, name, dimensions, startTime, endTime, offset, limit); List<MetricDefinition> metricDefs = new ArrayList<>(rows.size()); byte[] currentDefDimId = null; Map<String, String> dims = null; for (Map<String, Object> row : rows) { byte[] defDimId = (byte[]) row.get("defdimsid"); String metricName = (String) row.get("name"); String dimName = (String) row.get("dname"); String dimValue = (String) row.get("dvalue"); if (defDimId == null || !Arrays.equals(currentDefDimId, defDimId)) { currentDefDimId = defDimId; dims = new HashMap<>(); if (dimName != null && dimValue != null) { dims.put(dimName, dimValue); } MetricDefinition m = new MetricDefinition(metricName, dims); m.setId(Hex.encodeHexString(defDimId)); metricDefs.add(m); } else { dims.put(dimName, dimValue); } } return metricDefs; } private List<Map<String, Object>> executeMetricDefsQuery( String tenantId, String name, Map<String, String> dimensions, DateTime startTime, DateTime endTime, String offset, int limit) { String namePart = ""; if (name != null && !name.isEmpty()) { namePart = " and defSub.name = :name "; } String offsetPart = ""; if (offset != null && !offset.isEmpty()) { offsetPart = " and defdimsSub.id > :offset "; } // Can't bind limit in a nested sub query. So, just tack on as String. String limitPart = " limit " + Integer.toString(limit + 1); try (Handle h = db.open()) { // If startTime/endTime is specified, create the 'IN' select statement String timeInClause = createTimeInClause(h, startTime, endTime, tenantId, name, dimensions); String defSubSelect = String.format(METRIC_DEFINITIONS_SUB_SELECT, MetricQueries.buildJoinClauseFor(dimensions, TABLE_TO_JOIN_DIMENSIONS_ON), namePart, offsetPart, timeInClause, limitPart); String sql = String.format(FIND_METRIC_DEFS_SQL, defSubSelect); Query<Map<String, Object>> query = h.createQuery(sql).bind("tenantId", tenantId); if (name != null && !name.isEmpty()) { logger.debug("binding name: {}", name); query.bind("name", name); } if (startTime != null) { query.bind("start_time", startTime); } if (endTime != null) { query.bind("end_time", endTime); } if (offset != null && !offset.isEmpty()) { logger.debug("binding offset: {}", offset); try { query.bind("offset", Hex.decodeHex(offset.toCharArray())); } catch (DecoderException e) { throw Exceptions.badRequest("failed to decode offset " + offset, e); } } MetricQueries.bindDimensionsToQuery(query, dimensions); return query.list(); } } private String createTimeInClause( Handle dbHandle, DateTime startTime, DateTime endTime, String tenantId, String metricName, Map<String, String> dimensions) { if (startTime == null) { return ""; } Set<byte[]> defDimIdSet = new HashSet<>(); String namePart = ""; if (metricName != null && !metricName.isEmpty()) { namePart = "AND def.name = :name "; } String defDimSql = String.format(DEFDIM_IDS_SELECT, namePart, MetricQueries.buildJoinClauseFor(dimensions, "defDims")); Query<Map<String, Object>> query = dbHandle.createQuery(defDimSql).bind("tenantId", tenantId); DimensionQueries.bindDimensionsToQuery(query, dimensions); if (metricName != null && !metricName.isEmpty()) { query.bind("name", metricName); } List<Map<String, Object>> rows = query.list(); for (Map<String, Object> row : rows) { byte[] defDimId = (byte[]) row.get("id"); defDimIdSet.add(defDimId); } // // If we didn't find any definition dimension ids, // we won't add the time clause. // if (defDimIdSet.size() == 0) { return ""; } String timeAndClause = ""; if (endTime != null) { timeAndClause = "AND time_stamp >= :start_time AND time_stamp <= :end_time "; } else { timeAndClause = "AND time_stamp >= :start_time "; } String defDimInClause = MetricQueries.createDefDimIdInClause(defDimIdSet); return String.format(MEASUREMENT_AND_CLAUSE, defDimInClause, timeAndClause); } }
java/src/main/java/monasca/api/infrastructure/persistence/vertica/MetricDefinitionVerticaRepoImpl.java
/* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * 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 monasca.api.infrastructure.persistence.vertica; import monasca.api.domain.model.metric.MetricDefinitionRepo; import monasca.api.domain.model.metric.MetricName; import monasca.api.infrastructure.persistence.DimensionQueries; import monasca.api.resource.exception.Exceptions; import monasca.common.model.metric.MetricDefinition; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.joda.time.DateTime; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.Query; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; public class MetricDefinitionVerticaRepoImpl implements MetricDefinitionRepo { private static final Logger logger = LoggerFactory.getLogger(MetricDefinitionVerticaRepoImpl.class); private static final String FIND_METRIC_DEFS_SQL = "SELECT defDims.id as defDimsId, def.name, dims.name as dName, dims.value AS dValue " + "FROM MonMetrics.Definitions def, MonMetrics.DefinitionDimensions defDims " // Outer join needed in case there are no dimensions for a definition. + "LEFT OUTER JOIN MonMetrics.Dimensions dims ON dims.dimension_set_id = defDims" + ".dimension_set_id " + "WHERE def.id = defDims.definition_id " + "AND defDims.id IN (%s) " + "ORDER BY defDims.id ASC "; private static final String METRIC_DEFINITIONS_SUB_SELECT = "SELECT defDimsSub.id " + "FROM MonMetrics.Definitions defSub, MonMetrics.DefinitionDimensions defDimsSub" + "%s " // Dimensions inner join goes here if dimensions specified. + "WHERE defDimsSub.definition_id = defSub.id " + "AND defSub.tenant_id = :tenantId " + "%s " // Name goes here. + "%s " // Offset goes here. + "%s " // Optional timestamp qualifier goes here + "ORDER BY defdimsSub.id ASC %s"; // Limit goes here. private static final String FIND_METRIC_NAMES_SQL = "SELECT distinct def.id, def.name " + "FROM MonMetrics.Definitions def " + "WHERE def.id IN (%s) " + "ORDER BY def.id ASC "; private static final String METRIC_NAMES_SUB_SELECT = "SELECT defSub.id " + "FROM MonMetrics.Definitions defSub, MonMetrics.DefinitionDimensions defDimsSub" + "%s " // Dimensions inner join goes here if dimensions specified. + "WHERE defDimsSub.definition_id = defSub.id " + "AND defSub.tenant_id = :tenantId " + "%s " // Offset goes here. + "ORDER BY defSub.id ASC %s"; // Limit goes here. private static final String DEFDIM_IDS_SELECT = "SELECT defDims.id " + "FROM MonMetrics.Definitions def, MonMetrics.DefinitionDimensions defDims " + "WHERE defDims.definition_id = def.id " + "AND def.tenant_id = :tenantId " + "%s " // Name and clause here + "%s;"; // Dimensions and clause goes here private static final String MEASUREMENT_AND_CLAUSE = "AND defDims.id IN (" + "SELECT definition_dimensions_id FROM " + "MonMetrics.Measurements " + "WHERE to_hex(definition_dimensions_id) " + "%s " // List of definition dimension ids here + "%s ) "; // start or start and end time here private static final String TABLE_TO_JOIN_DIMENSIONS_ON = "defDimsSub"; private final DBI db; @Inject public MetricDefinitionVerticaRepoImpl(@Named("vertica") DBI db) { this.db = db; } @Override public List<MetricName> findNames( String tenantId, Map<String, String> dimensions, String offset, int limit) throws Exception { List<Map<String, Object>> rows = executeMetricNamesQuery(tenantId, dimensions, offset, limit); List<MetricName> metricNameList = new ArrayList<>(rows.size()); for (Map<String, Object> row : rows) { byte[] defId = (byte[]) row.get("id"); String name = (String) row.get("name"); MetricName metricName = new MetricName(Hex.encodeHexString(defId), name); metricNameList.add(metricName); } return metricNameList; } private List<Map<String, Object>> executeMetricNamesQuery( String tenantId, Map<String, String> dimensions, String offset, int limit) { String offsetPart = ""; if (offset != null && !offset.isEmpty()) { offsetPart = " and defSub.id > :offset "; } // Can't bind limit in a nested sub query. So, just tack on as String. String limitPart = " limit " + Integer.toString(limit + 1); String defSubSelect = String.format(METRIC_NAMES_SUB_SELECT, MetricQueries.buildJoinClauseFor(dimensions, TABLE_TO_JOIN_DIMENSIONS_ON), offsetPart, limitPart); String sql = String.format(FIND_METRIC_NAMES_SQL, defSubSelect); try (Handle h = db.open()) { Query<Map<String, Object>> query = h.createQuery(sql).bind("tenantId", tenantId); if (offset != null && !offset.isEmpty()) { logger.debug("binding offset: {}", offset); try { query.bind("offset", Hex.decodeHex(offset.toCharArray())); } catch (DecoderException e) { throw Exceptions.badRequest("failed to decode offset " + offset, e); } } DimensionQueries.bindDimensionsToQuery(query, dimensions); return query.list(); } } @Override public List<MetricDefinition> find( String tenantId, String name, Map<String, String> dimensions, DateTime startTime, DateTime endTime, String offset, int limit) { List<Map<String, Object>> rows = executeMetricDefsQuery(tenantId, name, dimensions, startTime, endTime, offset, limit); List<MetricDefinition> metricDefs = new ArrayList<>(rows.size()); byte[] currentDefDimId = null; Map<String, String> dims = null; for (Map<String, Object> row : rows) { byte[] defDimId = (byte[]) row.get("defdimsid"); String metricName = (String) row.get("name"); String dimName = (String) row.get("dname"); String dimValue = (String) row.get("dvalue"); if (defDimId == null || !Arrays.equals(currentDefDimId, defDimId)) { currentDefDimId = defDimId; dims = new HashMap<>(); if (dimName != null && dimValue != null) { dims.put(dimName, dimValue); } MetricDefinition m = new MetricDefinition(metricName, dims); m.setId(Hex.encodeHexString(defDimId)); metricDefs.add(m); } else { dims.put(dimName, dimValue); } } return metricDefs; } private List<Map<String, Object>> executeMetricDefsQuery( String tenantId, String name, Map<String, String> dimensions, DateTime startTime, DateTime endTime, String offset, int limit) { String namePart = ""; if (name != null && !name.isEmpty()) { namePart = " and defSub.name = :name "; } String offsetPart = ""; if (offset != null && !offset.isEmpty()) { offsetPart = " and defdimsSub.id > :offset "; } // Can't bind limit in a nested sub query. So, just tack on as String. String limitPart = " limit " + Integer.toString(limit + 1); try (Handle h = db.open()) { // If startTime/endTime is specified, create the 'IN' select statement String timeInClause = createTimeInClause(h, startTime, endTime, tenantId, name, dimensions); String defSubSelect = String.format(METRIC_DEFINITIONS_SUB_SELECT, MetricQueries.buildJoinClauseFor(dimensions, TABLE_TO_JOIN_DIMENSIONS_ON), namePart, offsetPart, timeInClause, limitPart); String sql = String.format(FIND_METRIC_DEFS_SQL, defSubSelect); Query<Map<String, Object>> query = h.createQuery(sql).bind("tenantId", tenantId); if (name != null && !name.isEmpty()) { logger.debug("binding name: {}", name); query.bind("name", name); } if (startTime != null) { query.bind("start_time", startTime); } if (endTime != null) { query.bind("end_time", endTime); } if (offset != null && !offset.isEmpty()) { logger.debug("binding offset: {}", offset); try { query.bind("offset", Hex.decodeHex(offset.toCharArray())); } catch (DecoderException e) { throw Exceptions.badRequest("failed to decode offset " + offset, e); } } MetricQueries.bindDimensionsToQuery(query, dimensions); return query.list(); } } private String createTimeInClause( Handle dbHandle, DateTime startTime, DateTime endTime, String tenantId, String metricName, Map<String, String> dimensions) { if (startTime == null) { return ""; } Set<byte[]> defDimIdSet = new HashSet<>(); String namePart = ""; if (metricName != null && !metricName.isEmpty()) { namePart = "AND def.name = :name "; } String defDimSql = String.format(DEFDIM_IDS_SELECT, namePart, MetricQueries.buildJoinClauseFor(dimensions, "defDims")); Query<Map<String, Object>> query = dbHandle.createQuery(defDimSql).bind("tenantId", tenantId); DimensionQueries.bindDimensionsToQuery(query, dimensions); if (metricName != null && !metricName.isEmpty()) { query.bind("name", metricName); } List<Map<String, Object>> rows = query.list(); for (Map<String, Object> row : rows) { byte[] defDimId = (byte[]) row.get("id"); defDimIdSet.add(defDimId); } // // If we didn't find any definition dimension ids, // we won't add the time clause. // if (defDimIdSet.size() == 0) { return ""; } String timeAndClause = ""; if (endTime != null) { timeAndClause = "AND time_stamp >= :start_time AND time_stamp <= :end_time "; } else { timeAndClause = "AND time_stamp >= :start_time "; } String defDimInClause = MetricQueries.createDefDimIdInClause(defDimIdSet); return String.format(MEASUREMENT_AND_CLAUSE, defDimInClause, timeAndClause); } }
Fix limit issue on metric names query in vertica Change the subquery to choose 5 distinct names, instead of definition ids Change-Id: I09e2cd230a2301245358c51b9a9a4b47f278918c
java/src/main/java/monasca/api/infrastructure/persistence/vertica/MetricDefinitionVerticaRepoImpl.java
Fix limit issue on metric names query in vertica
Java
apache-2.0
560d20332c1923ebdffed06f9925b7e1667c84c2
0
j-coll/opencga,opencb/opencga,opencb/opencga,j-coll/opencga,opencb/opencga,j-coll/opencga,opencb/opencga,j-coll/opencga,opencb/opencga,j-coll/opencga,j-coll/opencga,opencb/opencga
/* * Copyright 2015-2017 OpenCB * * 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.opencb.opencga.app.cli.main.executors.analysis; import com.google.protobuf.util.JsonFormat; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.internal.ManagedChannelImpl; import org.apache.commons.lang3.StringUtils; import org.opencb.biodata.models.common.protobuf.service.ServiceTypesModel; import org.opencb.biodata.models.variant.Variant; import org.opencb.biodata.models.variant.metadata.VariantMetadata; import org.opencb.biodata.models.variant.protobuf.VariantProto; import org.opencb.commons.datastore.core.*; import org.opencb.opencga.app.cli.analysis.executors.VariantQueryCommandUtils; import org.opencb.opencga.app.cli.analysis.options.VariantCommandOptions; import org.opencb.opencga.app.cli.main.executors.OpencgaCommandExecutor; import org.opencb.opencga.app.cli.main.io.VcfOutputWriter; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.core.results.VariantQueryResult; import org.opencb.opencga.server.grpc.AdminServiceGrpc; import org.opencb.opencga.server.grpc.GenericServiceModel; import org.opencb.opencga.server.grpc.VariantServiceGrpc; import org.opencb.opencga.storage.core.manager.variant.VariantStorageManager; import org.opencb.opencga.storage.core.manager.variant.operations.VariantFileIndexerStorageOperation; import org.opencb.opencga.storage.core.variant.VariantStorageEngine; import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam; import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryUtils; import org.opencb.opencga.storage.core.variant.annotation.VariantAnnotationManager; import java.io.IOException; import java.io.PrintStream; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; /** * Created by pfurio on 15/08/16. */ public class VariantCommandExecutor extends OpencgaCommandExecutor { private VariantCommandOptions variantCommandOptions; private ManagedChannel channel = null; public VariantCommandExecutor(VariantCommandOptions variantCommandOptions) { super(variantCommandOptions.commonCommandOptions); this.variantCommandOptions = variantCommandOptions; } @Override public void execute() throws Exception { logger.debug("Executing variant command line"); String subCommandString = getParsedSubCommand(variantCommandOptions.jCommander); QueryResponse queryResponse = null; switch (subCommandString) { case "index": queryResponse = index(); break; case "query": queryResponse = query(); break; default: logger.error("Subcommand not valid"); break; } // ObjectMapper objectMapper = new ObjectMapper(); // System.out.println(objectMapper.writeValueAsString(queryResponse.getResponse())); createOutput(queryResponse); } private QueryResponse index() throws CatalogException, IOException { logger.debug("Indexing variant(s)"); String fileIds = variantCommandOptions.indexVariantCommandOptions.fileId; ObjectMap o = new ObjectMap(); o.putIfNotNull(VariantStorageEngine.Options.STUDY_ID.key(), variantCommandOptions.indexVariantCommandOptions.study); o.putIfNotNull("outDir", variantCommandOptions.indexVariantCommandOptions.outdir); o.putIfNotNull(VariantFileIndexerStorageOperation.TRANSFORMED_FILES, variantCommandOptions.indexVariantCommandOptions.transformedPaths); o.putIfNotNull("transform", variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.transform); o.putIfNotNull("load", variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.load); o.putIfNotNull(VariantStorageEngine.Options.EXCLUDE_GENOTYPES.key(), variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.excludeGenotype); o.putIfNotNull("includeExtraFields", variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.extraFields); o.putIfNotNull("merge", variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.merge); o.putIfNotNull("aggregated", variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.aggregated); o.putIfNotNull(VariantStorageEngine.Options.CALCULATE_STATS.key(), variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.calculateStats); o.putIfNotNull(VariantStorageEngine.Options.ANNOTATE.key(), variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.annotate); o.putIfNotNull(VariantStorageEngine.Options.RESUME.key(), variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.resume); o.putIfNotNull(VariantStorageEngine.Options.LOAD_SPLIT_DATA.key(), variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.loadSplitData); o.putIfNotNull(VariantAnnotationManager.OVERWRITE_ANNOTATIONS, variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.overwriteAnnotations); o.putAll(variantCommandOptions.commonCommandOptions.params); // return openCGAClient.getFileClient().index(fileIds, o); return openCGAClient.getVariantClient().index(fileIds, o); } private QueryResponse query() throws CatalogException, IOException, InterruptedException { logger.debug("Listing variants of a study."); VariantCommandOptions.VariantQueryCommandOptions queryCommandOptions = variantCommandOptions.queryVariantCommandOptions; queryCommandOptions.study = resolveStudy(queryCommandOptions.study); queryCommandOptions.genericVariantQueryOptions.returnStudy = resolveStudy(queryCommandOptions.genericVariantQueryOptions.returnStudy); List<String> studies = new ArrayList<>(); if (cliSession != null && cliSession.getProjectsAndStudies() != null) { for (Map.Entry<String, List<String>> entry : cliSession.getProjectsAndStudies().entrySet()) { for (String s : entry.getValue()) { studies.add(entry.getKey() + ':' + s); } } } Query query = VariantQueryCommandUtils.parseQuery(queryCommandOptions, studies, clientConfiguration); QueryOptions options = VariantQueryCommandUtils.parseQueryOptions(queryCommandOptions); options.putIfNotEmpty("groupBy", queryCommandOptions.genericVariantQueryOptions.groupBy); options.put("histogram", queryCommandOptions.genericVariantQueryOptions.histogram); options.put("interval", queryCommandOptions.genericVariantQueryOptions.interval); options.put("rank", queryCommandOptions.genericVariantQueryOptions.rank); List<String> annotations = queryCommandOptions.genericVariantQueryOptions.annotations == null ? Collections.singletonList("gene") : Arrays.asList(queryCommandOptions.genericVariantQueryOptions.annotations.split(",")); // Let's hide some STDOUT verbose messages from ManagedChannelImpl class Logger.getLogger(ManagedChannelImpl.class.getName()).setLevel(java.util.logging.Level.WARNING); ObjectMap params = new ObjectMap(query); QueryOptions metadataQueryOptions = new QueryOptions(options); metadataQueryOptions.addToListOption(QueryOptions.EXCLUDE, "files"); metadataQueryOptions.append("basic", true); VariantMetadata metadata = openCGAClient.getVariantClient().metadata(params, metadataQueryOptions).firstResult(); VcfOutputWriter vcfOutputWriter = new VcfOutputWriter(metadata, annotations, System.out); boolean grpc = usingGrpcMode(queryCommandOptions.mode); if (!grpc) { if (queryCommandOptions.numericOptions.count) { return openCGAClient.getVariantClient().count(params, options); } else if (StringUtils.isNoneEmpty(queryCommandOptions.genericVariantQueryOptions.groupBy) || queryCommandOptions.genericVariantQueryOptions.histogram || StringUtils.isNoneEmpty(queryCommandOptions.genericVariantQueryOptions.rank)) { return openCGAClient.getVariantClient().genericQuery(params, options); } else { options.put(QueryOptions.SKIP_COUNT, true); params.put(VariantQueryParam.SAMPLE_METADATA.key(), true); if (queryCommandOptions.commonOptions.outputFormat.equalsIgnoreCase("vcf") || queryCommandOptions.commonOptions.outputFormat.equalsIgnoreCase("text")) { QueryResponse<Variant> queryResponse = openCGAClient.getVariantClient().query(params, options); vcfOutputWriter.print(queryResponse); return null; } else { return openCGAClient.getVariantClient().query(params, options); } } } else { ManagedChannel channel = getManagedChannel(); // We use a blocking stub to execute the query to gRPC VariantServiceGrpc.VariantServiceBlockingStub variantServiceBlockingStub = VariantServiceGrpc.newBlockingStub(channel); params.putAll(options); query = VariantStorageManager.getVariantQuery(params); Map<String, String> queryMap = new HashMap<>(); Map<String, String> queryOptionsMap = new HashMap<>(); for (String key : params.keySet()) { if (query.containsKey(key)) { queryMap.put(key, query.getString(key)); } else { queryOptionsMap.put(key, params.getString(key)); } } // We create the OpenCGA gRPC request object with the query, queryOptions and sessionId GenericServiceModel.Request request = GenericServiceModel.Request.newBuilder() .putAllQuery(queryMap) .putAllOptions(queryOptionsMap) .setSessionId(sessionId == null ? "" : sessionId) .build(); QueryResponse queryResponse = null; if (queryCommandOptions.numericOptions.count) { ServiceTypesModel.LongResponse countResponse = variantServiceBlockingStub.count(request); ServiceTypesModel.Response response = countResponse.getResponse(); queryResponse = new QueryResponse<>("", 0, response.getWarning(), response.getError(), new QueryOptions(params), Collections.singletonList( new QueryResult<>(response.getId(), 0, 1, 1, "", "", Collections.singletonList(countResponse.getValue())))); return queryResponse; } else if (queryCommandOptions.genericVariantQueryOptions.samplesMetadata || StringUtils.isNoneEmpty(queryCommandOptions.genericVariantQueryOptions.groupBy) || queryCommandOptions.genericVariantQueryOptions.histogram) { queryResponse = openCGAClient.getVariantClient().genericQuery(params, options); } else { Iterator<VariantProto.Variant> variantIterator = variantServiceBlockingStub.get(request); if (queryCommandOptions.commonOptions.outputFormat.equalsIgnoreCase("vcf") || queryCommandOptions.commonOptions.outputFormat.equalsIgnoreCase("text")) { options.put(QueryOptions.SKIP_COUNT, true); options.put(QueryOptions.LIMIT, 1); vcfOutputWriter.print(variantIterator); } else { JsonFormat.Printer printer = JsonFormat.printer(); try (PrintStream printStream = new PrintStream(System.out)) { while (variantIterator.hasNext()) { VariantProto.Variant next = variantIterator.next(); printStream.println(printer.print(next)); } } queryResponse = null; } } channel.shutdown().awaitTermination(2, TimeUnit.SECONDS); return queryResponse; } } private boolean usingGrpcMode(String mode) { final boolean grpc; switch (mode.toUpperCase()) { case "AUTO": grpc = isGrpcAvailable() == null; if (grpc) { logger.debug("Using GRPC mode"); } else { logger.debug("Using REST mode"); } break; case "GRPC": RuntimeException exception = isGrpcAvailable(); if (exception != null) { throw exception; } grpc = true; break; case "REST": grpc = false; break; default: throw new IllegalArgumentException("Unknown mode " + mode); } return grpc; } protected synchronized ManagedChannel getManagedChannel() { if (channel == null) { // Connecting to the server host and port String grpcServerHost = clientConfiguration.getGrpc().getHost(); logger.debug("Connecting to gRPC server at '{}'", grpcServerHost); // We create the gRPC channel to the specified server host and port channel = ManagedChannelBuilder.forTarget(grpcServerHost) .usePlaintext(true) .build(); } return channel; } protected RuntimeException isGrpcAvailable() { // Connecting to the server host and port try { ManagedChannel channel = getManagedChannel(); AdminServiceGrpc.AdminServiceBlockingStub stub = AdminServiceGrpc.newBlockingStub(channel); ServiceTypesModel.MapResponse status = stub.status(GenericServiceModel.Request.getDefaultInstance()); return null; } catch (RuntimeException e) { return e; } } private List<String> getSamplesFromVariantQueryResult(VariantQueryResult<Variant> variantQueryResult, String study) { Map<String, List<String>> samplePerStudy = new HashMap<>(); // Aggregated studies do not contain samples if (variantQueryResult.getSamples() != null) { // We have to remove the user and project from the Study name variantQueryResult.getSamples().forEach((st, sampleList) -> { String study1 = st.split(":")[1]; samplePerStudy.put(study1, sampleList); }); } // Prepare samples for the VCF header List<String> samples = null; if (StringUtils.isEmpty(study)) { if (samplePerStudy.size() == 1) { study = samplePerStudy.keySet().iterator().next(); samples = samplePerStudy.get(study); } } else { if (study.contains(":")) { study = study.split(":")[1]; } else { if (clientConfiguration.getAlias() != null && clientConfiguration.getAlias().get(study) != null) { study = clientConfiguration.getAlias().get(study); if (study.contains(":")) { study = study.split(":")[1]; } } } samples = samplePerStudy.get(study); } // TODO move this to biodata if (samples == null) { samples = new ArrayList<>(); } return samples; } @Override protected String resolveStudy(String study) { if (StringUtils.isEmpty(study)) { if (StringUtils.isNotEmpty(clientConfiguration.getDefaultStudy())) { return clientConfiguration.getDefaultStudy(); } } else { // study is not empty, let's check if it is an alias if (clientConfiguration.getAlias() != null && clientConfiguration.getAlias().size() > 0) { VariantQueryUtils.QueryOperation queryOperation = VariantQueryUtils.checkOperator(study); if (queryOperation == null) { queryOperation = VariantQueryUtils.QueryOperation.AND; } List<String> studies = VariantQueryUtils.splitValue(study, queryOperation); List<String> studyList = new ArrayList<>(studies.size()); for (String s : studies) { boolean negated = VariantQueryUtils.isNegated(s); if (negated) { // Remove negation to search alias s = VariantQueryUtils.removeNegation(s); } if (clientConfiguration.getAlias().containsKey(s)) { s = clientConfiguration.getAlias().get(study); } if (negated) { // restore negation s = VariantQueryUtils.NOT + s; } studyList.add(s); } return StringUtils.join(studyList, queryOperation.separator()); } } return study; } }
opencga-app/src/main/java/org/opencb/opencga/app/cli/main/executors/analysis/VariantCommandExecutor.java
/* * Copyright 2015-2017 OpenCB * * 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.opencb.opencga.app.cli.main.executors.analysis; import com.google.protobuf.util.JsonFormat; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.internal.ManagedChannelImpl; import org.apache.commons.lang3.StringUtils; import org.opencb.biodata.models.common.protobuf.service.ServiceTypesModel; import org.opencb.biodata.models.variant.Variant; import org.opencb.biodata.models.variant.metadata.VariantMetadata; import org.opencb.biodata.models.variant.protobuf.VariantProto; import org.opencb.commons.datastore.core.*; import org.opencb.opencga.app.cli.analysis.executors.VariantQueryCommandUtils; import org.opencb.opencga.app.cli.analysis.options.VariantCommandOptions; import org.opencb.opencga.app.cli.main.executors.OpencgaCommandExecutor; import org.opencb.opencga.app.cli.main.io.VcfOutputWriter; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.core.results.VariantQueryResult; import org.opencb.opencga.server.grpc.AdminServiceGrpc; import org.opencb.opencga.server.grpc.GenericServiceModel; import org.opencb.opencga.server.grpc.VariantServiceGrpc; import org.opencb.opencga.storage.core.manager.variant.VariantStorageManager; import org.opencb.opencga.storage.core.variant.VariantStorageEngine; import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam; import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryUtils; import org.opencb.opencga.storage.core.variant.annotation.VariantAnnotationManager; import java.io.IOException; import java.io.PrintStream; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; /** * Created by pfurio on 15/08/16. */ public class VariantCommandExecutor extends OpencgaCommandExecutor { private VariantCommandOptions variantCommandOptions; private ManagedChannel channel = null; public VariantCommandExecutor(VariantCommandOptions variantCommandOptions) { super(variantCommandOptions.commonCommandOptions); this.variantCommandOptions = variantCommandOptions; } @Override public void execute() throws Exception { logger.debug("Executing variant command line"); String subCommandString = getParsedSubCommand(variantCommandOptions.jCommander); QueryResponse queryResponse = null; switch (subCommandString) { case "index": queryResponse = index(); break; case "query": queryResponse = query(); break; default: logger.error("Subcommand not valid"); break; } // ObjectMapper objectMapper = new ObjectMapper(); // System.out.println(objectMapper.writeValueAsString(queryResponse.getResponse())); createOutput(queryResponse); } private QueryResponse index() throws CatalogException, IOException { logger.debug("Indexing variant(s)"); String fileIds = variantCommandOptions.indexVariantCommandOptions.fileId; ObjectMap o = new ObjectMap(); o.putIfNotNull(VariantStorageEngine.Options.STUDY_ID.key(), variantCommandOptions.indexVariantCommandOptions.study); o.putIfNotNull("outDir", variantCommandOptions.indexVariantCommandOptions.outdir); o.putIfNotNull("transform", variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.transform); o.putIfNotNull("load", variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.load); o.putIfNotNull(VariantStorageEngine.Options.EXCLUDE_GENOTYPES.key(), variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.excludeGenotype); o.putIfNotNull("includeExtraFields", variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.extraFields); o.putIfNotNull("merge", variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.merge); o.putIfNotNull("aggregated", variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.aggregated); o.putIfNotNull(VariantStorageEngine.Options.CALCULATE_STATS.key(), variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.calculateStats); o.putIfNotNull(VariantStorageEngine.Options.ANNOTATE.key(), variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.annotate); o.putIfNotNull(VariantStorageEngine.Options.RESUME.key(), variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.resume); o.putIfNotNull(VariantStorageEngine.Options.LOAD_SPLIT_DATA.key(), variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.loadSplitData); o.putIfNotNull(VariantAnnotationManager.OVERWRITE_ANNOTATIONS, variantCommandOptions.indexVariantCommandOptions.genericVariantIndexOptions.overwriteAnnotations); o.putAll(variantCommandOptions.commonCommandOptions.params); // return openCGAClient.getFileClient().index(fileIds, o); return openCGAClient.getVariantClient().index(fileIds, o); } private QueryResponse query() throws CatalogException, IOException, InterruptedException { logger.debug("Listing variants of a study."); VariantCommandOptions.VariantQueryCommandOptions queryCommandOptions = variantCommandOptions.queryVariantCommandOptions; queryCommandOptions.study = resolveStudy(queryCommandOptions.study); queryCommandOptions.genericVariantQueryOptions.returnStudy = resolveStudy(queryCommandOptions.genericVariantQueryOptions.returnStudy); List<String> studies = new ArrayList<>(); if (cliSession != null && cliSession.getProjectsAndStudies() != null) { for (Map.Entry<String, List<String>> entry : cliSession.getProjectsAndStudies().entrySet()) { for (String s : entry.getValue()) { studies.add(entry.getKey() + ':' + s); } } } Query query = VariantQueryCommandUtils.parseQuery(queryCommandOptions, studies, clientConfiguration); QueryOptions options = VariantQueryCommandUtils.parseQueryOptions(queryCommandOptions); options.putIfNotEmpty("groupBy", queryCommandOptions.genericVariantQueryOptions.groupBy); options.put("histogram", queryCommandOptions.genericVariantQueryOptions.histogram); options.put("interval", queryCommandOptions.genericVariantQueryOptions.interval); options.put("rank", queryCommandOptions.genericVariantQueryOptions.rank); List<String> annotations = queryCommandOptions.genericVariantQueryOptions.annotations == null ? Collections.singletonList("gene") : Arrays.asList(queryCommandOptions.genericVariantQueryOptions.annotations.split(",")); // Let's hide some STDOUT verbose messages from ManagedChannelImpl class Logger.getLogger(ManagedChannelImpl.class.getName()).setLevel(java.util.logging.Level.WARNING); ObjectMap params = new ObjectMap(query); QueryOptions metadataQueryOptions = new QueryOptions(options); metadataQueryOptions.addToListOption(QueryOptions.EXCLUDE, "files"); metadataQueryOptions.append("basic", true); VariantMetadata metadata = openCGAClient.getVariantClient().metadata(params, metadataQueryOptions).firstResult(); VcfOutputWriter vcfOutputWriter = new VcfOutputWriter(metadata, annotations, System.out); boolean grpc = usingGrpcMode(queryCommandOptions.mode); if (!grpc) { if (queryCommandOptions.numericOptions.count) { return openCGAClient.getVariantClient().count(params, options); } else if (StringUtils.isNoneEmpty(queryCommandOptions.genericVariantQueryOptions.groupBy) || queryCommandOptions.genericVariantQueryOptions.histogram || StringUtils.isNoneEmpty(queryCommandOptions.genericVariantQueryOptions.rank)) { return openCGAClient.getVariantClient().genericQuery(params, options); } else { options.put(QueryOptions.SKIP_COUNT, true); params.put(VariantQueryParam.SAMPLE_METADATA.key(), true); if (queryCommandOptions.commonOptions.outputFormat.equalsIgnoreCase("vcf") || queryCommandOptions.commonOptions.outputFormat.equalsIgnoreCase("text")) { QueryResponse<Variant> queryResponse = openCGAClient.getVariantClient().query(params, options); vcfOutputWriter.print(queryResponse); return null; } else { return openCGAClient.getVariantClient().query(params, options); } } } else { ManagedChannel channel = getManagedChannel(); // We use a blocking stub to execute the query to gRPC VariantServiceGrpc.VariantServiceBlockingStub variantServiceBlockingStub = VariantServiceGrpc.newBlockingStub(channel); params.putAll(options); query = VariantStorageManager.getVariantQuery(params); Map<String, String> queryMap = new HashMap<>(); Map<String, String> queryOptionsMap = new HashMap<>(); for (String key : params.keySet()) { if (query.containsKey(key)) { queryMap.put(key, query.getString(key)); } else { queryOptionsMap.put(key, params.getString(key)); } } // We create the OpenCGA gRPC request object with the query, queryOptions and sessionId GenericServiceModel.Request request = GenericServiceModel.Request.newBuilder() .putAllQuery(queryMap) .putAllOptions(queryOptionsMap) .setSessionId(sessionId == null ? "" : sessionId) .build(); QueryResponse queryResponse = null; if (queryCommandOptions.numericOptions.count) { ServiceTypesModel.LongResponse countResponse = variantServiceBlockingStub.count(request); ServiceTypesModel.Response response = countResponse.getResponse(); queryResponse = new QueryResponse<>("", 0, response.getWarning(), response.getError(), new QueryOptions(params), Collections.singletonList( new QueryResult<>(response.getId(), 0, 1, 1, "", "", Collections.singletonList(countResponse.getValue())))); return queryResponse; } else if (queryCommandOptions.genericVariantQueryOptions.samplesMetadata || StringUtils.isNoneEmpty(queryCommandOptions.genericVariantQueryOptions.groupBy) || queryCommandOptions.genericVariantQueryOptions.histogram) { queryResponse = openCGAClient.getVariantClient().genericQuery(params, options); } else { Iterator<VariantProto.Variant> variantIterator = variantServiceBlockingStub.get(request); if (queryCommandOptions.commonOptions.outputFormat.equalsIgnoreCase("vcf") || queryCommandOptions.commonOptions.outputFormat.equalsIgnoreCase("text")) { options.put(QueryOptions.SKIP_COUNT, true); options.put(QueryOptions.LIMIT, 1); vcfOutputWriter.print(variantIterator); } else { JsonFormat.Printer printer = JsonFormat.printer(); try (PrintStream printStream = new PrintStream(System.out)) { while (variantIterator.hasNext()) { VariantProto.Variant next = variantIterator.next(); printStream.println(printer.print(next)); } } queryResponse = null; } } channel.shutdown().awaitTermination(2, TimeUnit.SECONDS); return queryResponse; } } private boolean usingGrpcMode(String mode) { final boolean grpc; switch (mode.toUpperCase()) { case "AUTO": grpc = isGrpcAvailable() == null; if (grpc) { logger.debug("Using GRPC mode"); } else { logger.debug("Using REST mode"); } break; case "GRPC": RuntimeException exception = isGrpcAvailable(); if (exception != null) { throw exception; } grpc = true; break; case "REST": grpc = false; break; default: throw new IllegalArgumentException("Unknown mode " + mode); } return grpc; } protected synchronized ManagedChannel getManagedChannel() { if (channel == null) { // Connecting to the server host and port String grpcServerHost = clientConfiguration.getGrpc().getHost(); logger.debug("Connecting to gRPC server at '{}'", grpcServerHost); // We create the gRPC channel to the specified server host and port channel = ManagedChannelBuilder.forTarget(grpcServerHost) .usePlaintext(true) .build(); } return channel; } protected RuntimeException isGrpcAvailable() { // Connecting to the server host and port try { ManagedChannel channel = getManagedChannel(); AdminServiceGrpc.AdminServiceBlockingStub stub = AdminServiceGrpc.newBlockingStub(channel); ServiceTypesModel.MapResponse status = stub.status(GenericServiceModel.Request.getDefaultInstance()); return null; } catch (RuntimeException e) { return e; } } private List<String> getSamplesFromVariantQueryResult(VariantQueryResult<Variant> variantQueryResult, String study) { Map<String, List<String>> samplePerStudy = new HashMap<>(); // Aggregated studies do not contain samples if (variantQueryResult.getSamples() != null) { // We have to remove the user and project from the Study name variantQueryResult.getSamples().forEach((st, sampleList) -> { String study1 = st.split(":")[1]; samplePerStudy.put(study1, sampleList); }); } // Prepare samples for the VCF header List<String> samples = null; if (StringUtils.isEmpty(study)) { if (samplePerStudy.size() == 1) { study = samplePerStudy.keySet().iterator().next(); samples = samplePerStudy.get(study); } } else { if (study.contains(":")) { study = study.split(":")[1]; } else { if (clientConfiguration.getAlias() != null && clientConfiguration.getAlias().get(study) != null) { study = clientConfiguration.getAlias().get(study); if (study.contains(":")) { study = study.split(":")[1]; } } } samples = samplePerStudy.get(study); } // TODO move this to biodata if (samples == null) { samples = new ArrayList<>(); } return samples; } @Override protected String resolveStudy(String study) { if (StringUtils.isEmpty(study)) { if (StringUtils.isNotEmpty(clientConfiguration.getDefaultStudy())) { return clientConfiguration.getDefaultStudy(); } } else { // study is not empty, let's check if it is an alias if (clientConfiguration.getAlias() != null && clientConfiguration.getAlias().size() > 0) { VariantQueryUtils.QueryOperation queryOperation = VariantQueryUtils.checkOperator(study); if (queryOperation == null) { queryOperation = VariantQueryUtils.QueryOperation.AND; } List<String> studies = VariantQueryUtils.splitValue(study, queryOperation); List<String> studyList = new ArrayList<>(studies.size()); for (String s : studies) { boolean negated = VariantQueryUtils.isNegated(s); if (negated) { // Remove negation to search alias s = VariantQueryUtils.removeNegation(s); } if (clientConfiguration.getAlias().containsKey(s)) { s = clientConfiguration.getAlias().get(study); } if (negated) { // restore negation s = VariantQueryUtils.NOT + s; } studyList.add(s); } return StringUtils.join(studyList, queryOperation.separator()); } } return study; } }
app: Ensure all params from variant index are parsed.
opencga-app/src/main/java/org/opencb/opencga/app/cli/main/executors/analysis/VariantCommandExecutor.java
app: Ensure all params from variant index are parsed.
Java
apache-2.0
c3ba25fcf58d3a2ea43f90e9e673784f2113fe21
0
prestodb/benchto,prestodb/benchto,prestodb/benchto,prestodb/benchto
/* * 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.teradata.benchto.driver.listeners.benchmark; import com.facebook.presto.jdbc.internal.guava.collect.Ordering; import com.google.common.collect.ImmutableList; import com.teradata.benchto.driver.Benchmark; import com.teradata.benchto.driver.execution.BenchmarkExecutionResult; import com.teradata.benchto.driver.execution.QueryExecution; import com.teradata.benchto.driver.execution.QueryExecutionResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.OrderComparator; import org.springframework.core.Ordered; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; import java.util.concurrent.Future; import java.util.function.BiFunction; @Component public class BenchmarkStatusReporter { @Autowired private List<BenchmarkExecutionListener> executionListeners; @PostConstruct public void sortExecutionListeners() { // HACK: listeners have to be sorted to provide tests determinism executionListeners = ImmutableList.copyOf( Ordering.<Ordered>from(OrderComparator.INSTANCE::compare) .compound(Ordering.usingToString()) .sortedCopy(executionListeners)); } public void reportBenchmarkStarted(Benchmark benchmark) { fireListeners(BenchmarkExecutionListener::benchmarkStarted, benchmark); } public void reportBenchmarkFinished(BenchmarkExecutionResult benchmarkExecutionResult) { fireListeners(BenchmarkExecutionListener::benchmarkFinished, benchmarkExecutionResult); } public void reportExecutionStarted(QueryExecution queryExecution) { fireListeners(BenchmarkExecutionListener::executionStarted, queryExecution); } public void reportExecutionFinished(QueryExecutionResult queryExecutionResult) { fireListeners(BenchmarkExecutionListener::executionFinished, queryExecutionResult); } private <T> void fireListeners(BiFunction<BenchmarkExecutionListener, T, Future<?>> invoker, T argument) { for (BenchmarkExecutionListener listener : executionListeners) { invoker.apply(listener, argument); } } }
benchto-driver/src/main/java/com/teradata/benchto/driver/listeners/benchmark/BenchmarkStatusReporter.java
/* * 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.teradata.benchto.driver.listeners.benchmark; import com.facebook.presto.jdbc.internal.guava.collect.Ordering; import com.google.common.collect.ImmutableList; import com.teradata.benchto.driver.Benchmark; import com.teradata.benchto.driver.execution.BenchmarkExecutionResult; import com.teradata.benchto.driver.execution.QueryExecution; import com.teradata.benchto.driver.execution.QueryExecutionResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.OrderComparator; import org.springframework.core.Ordered; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; @Component public class BenchmarkStatusReporter { @Autowired private List<BenchmarkExecutionListener> executionListeners; @PostConstruct public void sortExecutionListeners() { // HACK: listeners have to be sorted to provide tests determinism executionListeners = ImmutableList.copyOf( Ordering.<Ordered>from(OrderComparator.INSTANCE::compare) .compound(Ordering.usingToString()) .sortedCopy(executionListeners)); } public void reportBenchmarkStarted(Benchmark benchmark) { for (BenchmarkExecutionListener listener : executionListeners) { listener.benchmarkStarted(benchmark); } } public void reportBenchmarkFinished(BenchmarkExecutionResult benchmarkExecutionResult) { for (BenchmarkExecutionListener listener : executionListeners) { listener.benchmarkFinished(benchmarkExecutionResult); } } public void reportExecutionStarted(QueryExecution queryExecution) { for (BenchmarkExecutionListener listener : executionListeners) { listener.executionStarted(queryExecution); } } public void reportExecutionFinished(QueryExecutionResult queryExecutionResult) { for (BenchmarkExecutionListener listener : executionListeners) { listener.executionFinished(queryExecutionResult); } } }
Refactor BenchmarkStatusReporter Refactor BenchmarkStatusReporter so that iterating over listeners and handling invocation result is in one place.
benchto-driver/src/main/java/com/teradata/benchto/driver/listeners/benchmark/BenchmarkStatusReporter.java
Refactor BenchmarkStatusReporter
Java
apache-2.0
7d53d9a8836ce4408de2a8ca7057b47b1b1ef2d7
0
grgrzybek/karaf,grgrzybek/karaf,grgrzybek/karaf
/* * 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.karaf.shell.impl.console.osgi.secured; import java.nio.file.Path; import java.security.AccessControlContext; import java.security.AccessController; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; import java.util.Dictionary; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.security.auth.Subject; import org.apache.felix.gogo.runtime.CommandNotFoundException; import org.apache.felix.gogo.runtime.CommandSessionImpl; import org.apache.felix.service.command.Function; import org.apache.felix.service.threadio.ThreadIO; import org.apache.karaf.jaas.boot.principal.RolePrincipal; import org.apache.karaf.service.guard.tools.ACLConfigurationParser; import org.apache.karaf.shell.api.console.Command; import org.apache.karaf.shell.api.console.Session; import org.apache.karaf.shell.impl.console.SessionFactoryImpl; import org.apache.karaf.util.tracker.SingleServiceTracker; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.cm.ConfigurationEvent; import org.osgi.service.cm.ConfigurationListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SecuredSessionFactoryImpl extends SessionFactoryImpl implements ConfigurationListener { private static final String PROXY_COMMAND_ACL_PID_PREFIX = "org.apache.karaf.command.acl."; private static final String CONFIGURATION_FILTER = "(" + Constants.SERVICE_PID + "=" + PROXY_COMMAND_ACL_PID_PREFIX + "*)"; private static final String SHELL_SCOPE = "shell"; private static final String SHELL_INVOKE = ".invoke"; private static final String SHELL_REDIRECT = ".redirect"; private static final Logger LOGGER = LoggerFactory.getLogger(SecuredSessionFactoryImpl.class); private BundleContext bundleContext; private Map<String, Dictionary<String, Object>> scopes = new HashMap<>(); private SingleServiceTracker<ConfigurationAdmin> configAdminTracker; private ServiceRegistration<ConfigurationListener> registration; private ThreadLocal<Map<Object, Boolean>> serviceVisibleMap = new ThreadLocal<>(); public SecuredSessionFactoryImpl(BundleContext bundleContext, ThreadIO threadIO) throws InvalidSyntaxException { super(threadIO); this.bundleContext = bundleContext; this.registration = bundleContext.registerService(ConfigurationListener.class, this, null); this.configAdminTracker = new SingleServiceTracker<>(bundleContext, ConfigurationAdmin.class, this::update); this.configAdminTracker.open(); } public void stop() { this.registration.unregister(); this.configAdminTracker.close(); super.stop(); } @Override protected Object invoke(CommandSessionImpl session, Object target, String name, List<Object> args) throws Exception { checkSecurity(SHELL_SCOPE, SHELL_INVOKE, Arrays.asList(target, name, args)); return super.invoke(session, target, name, args); } @Override protected Path redirect(CommandSessionImpl session, Path path, int mode) { checkSecurity(SHELL_SCOPE, SHELL_REDIRECT, Arrays.asList(path, mode)); return super.redirect(session, path, mode); } @Override protected Function wrap(Command command) { return new SecuredCommand(this, command); } @Override protected boolean isVisible(Object service) { if (this.serviceVisibleMap.get() == null) { this.serviceVisibleMap.set(new HashMap<>()); } if (this.serviceVisibleMap.get().get(service) != null) { return this.serviceVisibleMap.get().get(service); } if (service instanceof Command) { Command cmd = (Command) service; boolean ret = isVisible(cmd.getScope(), cmd.getName()); this.serviceVisibleMap.get().put(service, ret); return ret; } else { boolean ret = super.isVisible(service); this.serviceVisibleMap.get().put(service, ret); return ret; } } public boolean isVisible(String scope, String name) { boolean visible = true; Dictionary<String, Object> config = getScopeConfig(scope); if (config != null) { visible = false; List<String> roles = new ArrayList<>(); ACLConfigurationParser.getRolesForInvocation(name, null, null, config, roles); if (roles.isEmpty()) { visible = true; } else { for (String role : roles) { if (currentUserHasRole(role)) { visible = true; } } } } AliasCommand aliasCommand = findAlias(scope, name); if (aliasCommand != null) { visible = visible && isAliasVisible(aliasCommand.getScope(), aliasCommand.getName()); } return visible; } public boolean isAliasVisible(String scope, String name) { Dictionary<String, Object> config = getScopeConfig(scope); if (config != null) { List<String> roles = new ArrayList<>(); ACLConfigurationParser.getRolesForInvocationForAlias(name, null, null, config, roles); if (roles.isEmpty()) { return true; } else { for (String role : roles) { if (currentUserHasRole(role)) { return true; } } return false; } } return true; } private AliasCommand findAlias(String scope, String name) { if (session != null) { Set<String> vars = ((Set<String>) session.get(null)); Set<String> aliases = new HashSet<>(); String aliasScope = null; String aliasName = null; for (String var : vars) { Object content = session.get(var); if (content != null && "org.apache.felix.gogo.runtime.Closure".equals(content.getClass().getName())) { int index = var.indexOf(":"); if (index > 0) { aliasScope = var.substring(0, index); aliasName = var.substring(index + 1); String originalCmd = content.toString(); index = originalCmd.indexOf(" "); Object securityCmd = null; if (index > 0) { securityCmd = ((org.apache.felix.gogo.runtime.Closure)content) .get(originalCmd.substring(0, index)); } if (securityCmd instanceof SecuredCommand) { if (((SecuredCommand)securityCmd).getScope().equals(scope) && ((SecuredCommand)securityCmd).getName().equals(name)) { return new AliasCommand(aliasScope, aliasName); } } } } } } return null; } void checkSecurity(String scope, String name, List<Object> arguments) { Dictionary<String, Object> config = getScopeConfig(scope); boolean passCheck = false; if (config != null) { if (!isVisible(scope, name)) { throw new CommandNotFoundException(scope + ":" + name); } List<String> roles = new ArrayList<>(); ACLConfigurationParser.Specificity s = ACLConfigurationParser.getRolesForInvocation(name, new Object[] { arguments.toString() }, null, config, roles); if (s == ACLConfigurationParser.Specificity.NO_MATCH) { passCheck = true; } for (String role : roles) { if (currentUserHasRole(role)) { passCheck = true; } } if (!passCheck) { throw new SecurityException("Insufficient credentials."); } } else { List<String> roles = new ArrayList<>(); ACLConfigurationParser.getCompulsoryRoles(roles); if (roles.size() == 0) { passCheck = true; } for (String role : roles) { if (currentUserHasRole(role)) { passCheck = true; } } if (!passCheck) { throw new SecurityException("Insufficient credentials."); } } AliasCommand aliasCommand = findAlias(scope, name); if (aliasCommand != null) { //this is the alias if (config != null) { if (!isAliasVisible(aliasCommand.getScope(), aliasCommand.getName())) { throw new CommandNotFoundException(aliasCommand.getScope() + ":" + aliasCommand.getName()); } List<String> roles = new ArrayList<>(); ACLConfigurationParser.Specificity s = ACLConfigurationParser.getRolesForInvocationForAlias(aliasCommand.getName(), new Object[] { arguments.toString() }, null, config, roles); if (s == ACLConfigurationParser.Specificity.NO_MATCH) { return; } for (String role : roles) { if (currentUserHasRole(role)) { return; } } throw new SecurityException("Insufficient credentials."); } } } static boolean currentUserHasRole(String requestedRole) { String clazz; String role; int index = requestedRole.indexOf(':'); if (index > 0) { clazz = requestedRole.substring(0, index); role = requestedRole.substring(index + 1); } else { clazz = RolePrincipal.class.getName(); role = requestedRole; } AccessControlContext acc = AccessController.getContext(); if (acc == null) { return false; } Subject subject = Subject.getSubject(acc); if (subject == null) { return false; } for (Principal p : subject.getPrincipals()) { if (clazz.equals(p.getClass().getName()) && role.equals(p.getName())) { return true; } } return false; } @Override public void configurationEvent(ConfigurationEvent event) { if (!event.getPid().startsWith(PROXY_COMMAND_ACL_PID_PREFIX)) return; try { synchronized(this.serviceVisibleMap) { if (this.serviceVisibleMap.get() != null) { this.serviceVisibleMap.get().clear(); } } switch (event.getType()) { case ConfigurationEvent.CM_DELETED: removeScopeConfig(event.getPid().substring(PROXY_COMMAND_ACL_PID_PREFIX.length())); break; case ConfigurationEvent.CM_UPDATED: ConfigurationAdmin configAdmin = bundleContext.getService(event.getReference()); try { addScopeConfig(configAdmin.getConfiguration(event.getPid(), null)); } finally { bundleContext.ungetService(event.getReference()); } break; } } catch (Exception e) { LOGGER.error("Problem processing Configuration Event {}", event, e); } } private void addScopeConfig(Configuration config) { if (!config.getPid().startsWith(PROXY_COMMAND_ACL_PID_PREFIX)) { // not a command scope configuration file return; } String scope = config.getPid().substring(PROXY_COMMAND_ACL_PID_PREFIX.length()); if (scope.indexOf('.') >= 0) { // scopes don't contains dots, not a command scope return; } scope = scope.trim(); synchronized (scopes) { if (scope.endsWith("*")) { scope = "star"; } scopes.put(scope, config.getProperties()); } } private void removeScopeConfig(String scope) { synchronized (scopes) { scopes.remove(scope); } } private Dictionary<String, Object> getScopeConfig(String scope) { synchronized (scopes) { if (scope.equals("*")) { scope = "star"; } return scopes.get(scope); } } protected void update(ConfigurationAdmin prev, ConfigurationAdmin configAdmin) { try { Configuration[] configs = configAdmin.listConfigurations(CONFIGURATION_FILTER); if (configs != null) { for (Configuration config : configs) { addScopeConfig(config); } } } catch (Exception e) { // Ignore, should never happen } } }
shell/core/src/main/java/org/apache/karaf/shell/impl/console/osgi/secured/SecuredSessionFactoryImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.karaf.shell.impl.console.osgi.secured; import java.nio.file.Path; import java.security.AccessControlContext; import java.security.AccessController; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; import java.util.Dictionary; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.security.auth.Subject; import org.apache.felix.gogo.runtime.CommandNotFoundException; import org.apache.felix.gogo.runtime.CommandSessionImpl; import org.apache.felix.service.command.Function; import org.apache.felix.service.threadio.ThreadIO; import org.apache.karaf.jaas.boot.principal.RolePrincipal; import org.apache.karaf.service.guard.tools.ACLConfigurationParser; import org.apache.karaf.shell.api.console.Command; import org.apache.karaf.shell.api.console.Session; import org.apache.karaf.shell.impl.console.SessionFactoryImpl; import org.apache.karaf.util.tracker.SingleServiceTracker; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.cm.ConfigurationEvent; import org.osgi.service.cm.ConfigurationListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SecuredSessionFactoryImpl extends SessionFactoryImpl implements ConfigurationListener { private static final String PROXY_COMMAND_ACL_PID_PREFIX = "org.apache.karaf.command.acl."; private static final String CONFIGURATION_FILTER = "(" + Constants.SERVICE_PID + "=" + PROXY_COMMAND_ACL_PID_PREFIX + "*)"; private static final String SHELL_SCOPE = "shell"; private static final String SHELL_INVOKE = ".invoke"; private static final String SHELL_REDIRECT = ".redirect"; private static final Logger LOGGER = LoggerFactory.getLogger(SecuredSessionFactoryImpl.class); private BundleContext bundleContext; private Map<String, Dictionary<String, Object>> scopes = new HashMap<>(); private SingleServiceTracker<ConfigurationAdmin> configAdminTracker; private ServiceRegistration<ConfigurationListener> registration; private ThreadLocal<Map<Object, Boolean>> serviceVisibleMap = new ThreadLocal<>(); public SecuredSessionFactoryImpl(BundleContext bundleContext, ThreadIO threadIO) throws InvalidSyntaxException { super(threadIO); this.bundleContext = bundleContext; this.registration = bundleContext.registerService(ConfigurationListener.class, this, null); this.configAdminTracker = new SingleServiceTracker<>(bundleContext, ConfigurationAdmin.class, this::update); this.configAdminTracker.open(); } public void stop() { this.registration.unregister(); this.configAdminTracker.close(); super.stop(); } @Override protected Object invoke(CommandSessionImpl session, Object target, String name, List<Object> args) throws Exception { checkSecurity(SHELL_SCOPE, SHELL_INVOKE, Arrays.asList(target, name, args)); return super.invoke(session, target, name, args); } @Override protected Path redirect(CommandSessionImpl session, Path path, int mode) { checkSecurity(SHELL_SCOPE, SHELL_REDIRECT, Arrays.asList(path, mode)); return super.redirect(session, path, mode); } @Override protected Function wrap(Command command) { return new SecuredCommand(this, command); } @Override protected boolean isVisible(Object service) { if (this.serviceVisibleMap.get() == null) { this.serviceVisibleMap.set(new HashMap<>()); } if (this.serviceVisibleMap.get().get(service) != null) { return this.serviceVisibleMap.get().get(service); } if (service instanceof Command) { Command cmd = (Command) service; boolean ret = isVisible(cmd.getScope(), cmd.getName()); this.serviceVisibleMap.get().put(service, ret); return ret; } else { boolean ret = super.isVisible(service); this.serviceVisibleMap.get().put(service, ret); return ret; } } public boolean isVisible(String scope, String name) { boolean visible = true; Dictionary<String, Object> config = getScopeConfig(scope); if (config != null) { visible = false; List<String> roles = new ArrayList<>(); ACLConfigurationParser.getRolesForInvocation(name, null, null, config, roles); if (roles.isEmpty()) { visible = true; } else { for (String role : roles) { if (currentUserHasRole(role)) { visible = true; } } } } AliasCommand aliasCommand = findAlias(scope, name); if (aliasCommand != null) { visible = visible && isAliasVisible(aliasCommand.getScope(), aliasCommand.getName()); } return visible; } public boolean isAliasVisible(String scope, String name) { Dictionary<String, Object> config = getScopeConfig(scope); if (config != null) { List<String> roles = new ArrayList<>(); ACLConfigurationParser.getRolesForInvocationForAlias(name, null, null, config, roles); if (roles.isEmpty()) { return true; } else { for (String role : roles) { if (currentUserHasRole(role)) { return true; } } return false; } } return true; } private AliasCommand findAlias(String scope, String name) { if (session != null) { Set<String> vars = ((Set<String>) session.get(null)); Set<String> aliases = new HashSet<>(); String aliasScope = null; String aliasName = null; for (String var : vars) { Object content = session.get(var); if (content != null && "org.apache.felix.gogo.runtime.Closure".equals(content.getClass().getName())) { int index = var.indexOf(":"); if (index > 0) { aliasScope = var.substring(0, index); aliasName = var.substring(index + 1); String originalCmd = content.toString(); index = originalCmd.indexOf(" "); Object securityCmd = null; if (index > 0) { securityCmd = ((org.apache.felix.gogo.runtime.Closure)content) .get(originalCmd.substring(0, index)); } if (securityCmd instanceof SecuredCommand) { if (((SecuredCommand)securityCmd).getScope().equals(scope) && ((SecuredCommand)securityCmd).getName().equals(name)) { return new AliasCommand(aliasScope, aliasName); } } } } } } return null; } void checkSecurity(String scope, String name, List<Object> arguments) { Dictionary<String, Object> config = getScopeConfig(scope); boolean passCheck = false; if (config != null) { if (!isVisible(scope, name)) { throw new CommandNotFoundException(scope + ":" + name); } List<String> roles = new ArrayList<>(); ACLConfigurationParser.Specificity s = ACLConfigurationParser.getRolesForInvocation(name, new Object[] { arguments.toString() }, null, config, roles); if (s == ACLConfigurationParser.Specificity.NO_MATCH) { passCheck = true; } for (String role : roles) { if (currentUserHasRole(role)) { passCheck = true; } } if (!passCheck) { throw new SecurityException("Insufficient credentials."); } } else { List<String> roles = new ArrayList<>(); ACLConfigurationParser.getCompulsoryRoles(roles); if (roles.size() == 0) { passCheck = true; } for (String role : roles) { if (currentUserHasRole(role)) { passCheck = true; } } if (!passCheck) { throw new SecurityException("Insufficient credentials."); } } AliasCommand aliasCommand = findAlias(scope, name); if (aliasCommand != null) { //this is the alias if (config != null) { if (!isAliasVisible(aliasCommand.getScope(), aliasCommand.getName())) { throw new CommandNotFoundException(aliasCommand.getScope() + ":" + aliasCommand.getName()); } List<String> roles = new ArrayList<>(); ACLConfigurationParser.Specificity s = ACLConfigurationParser.getRolesForInvocationForAlias(aliasCommand.getName(), new Object[] { arguments.toString() }, null, config, roles); if (s == ACLConfigurationParser.Specificity.NO_MATCH) { return; } for (String role : roles) { if (currentUserHasRole(role)) { return; } } throw new SecurityException("Insufficient credentials."); } } } static boolean currentUserHasRole(String requestedRole) { String clazz; String role; int index = requestedRole.indexOf(':'); if (index > 0) { clazz = requestedRole.substring(0, index); role = requestedRole.substring(index + 1); } else { clazz = RolePrincipal.class.getName(); role = requestedRole; } AccessControlContext acc = AccessController.getContext(); if (acc == null) { return false; } Subject subject = Subject.getSubject(acc); if (subject == null) { return false; } for (Principal p : subject.getPrincipals()) { if (clazz.equals(p.getClass().getName()) && role.equals(p.getName())) { return true; } } return false; } @Override public void configurationEvent(ConfigurationEvent event) { if (!event.getPid().startsWith(PROXY_COMMAND_ACL_PID_PREFIX)) return; try { synchronized(this.serviceVisibleMap) { if (this.serviceVisibleMap.get() != null) { this.serviceVisibleMap.get().clear(); } } switch (event.getType()) { case ConfigurationEvent.CM_DELETED: removeScopeConfig(event.getPid().substring(PROXY_COMMAND_ACL_PID_PREFIX.length())); break; case ConfigurationEvent.CM_UPDATED: ConfigurationAdmin configAdmin = bundleContext.getService(event.getReference()); try { addScopeConfig(configAdmin.getConfiguration(event.getPid(), null)); } finally { bundleContext.ungetService(event.getReference()); } break; } } catch (Exception e) { LOGGER.error("Problem processing Configuration Event {}", event, e); } } private void addScopeConfig(Configuration config) { if (!config.getPid().startsWith(PROXY_COMMAND_ACL_PID_PREFIX)) { // not a command scope configuration file return; } String scope = config.getPid().substring(PROXY_COMMAND_ACL_PID_PREFIX.length()); if (scope.indexOf('.') >= 0) { // scopes don't contains dots, not a command scope return; } scope = scope.trim(); synchronized (scopes) { scopes.put(scope, config.getProperties()); } } private void removeScopeConfig(String scope) { synchronized (scopes) { scopes.remove(scope); } } private Dictionary<String, Object> getScopeConfig(String scope) { synchronized (scopes) { return scopes.get(scope); } } protected void update(ConfigurationAdmin prev, ConfigurationAdmin configAdmin) { try { Configuration[] configs = configAdmin.listConfigurations(CONFIGURATION_FILTER); if (configs != null) { for (Configuration config : configs) { addScopeConfig(config); } } } catch (Exception e) { // Ignore, should never happen } } }
[KARAF-5700]handle \* scope specifically for ACL match
shell/core/src/main/java/org/apache/karaf/shell/impl/console/osgi/secured/SecuredSessionFactoryImpl.java
[KARAF-5700]handle \* scope specifically for ACL match
Java
apache-2.0
121a652e531a9b514dd8ef5a414d630f9380f5f8
0
webfd/hbasene,akkumar/hbasene
/** * Copyright 2010 Karthik Kumar * * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hbasene.index.search; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.apache.log4j.Logger; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.util.Version; import org.testng.annotations.Test; import com.hbasene.index.AbstractHBaseneTest; import com.hbasene.index.search.HBaseIndexSearcher; public class TestHBaseIndexSearcher extends AbstractHBaseneTest { private static final Logger LOG = Logger .getLogger(TestHBaseIndexSearcher.class.getName()); private static final String[] AIRPORTS = { "NYC", "JFK", "EWR", "SEA", "SFO", "OAK", "SJC" }; private final Map<String, List<Integer>> airportMap = new HashMap<String, List<Integer>>(); private HBaseIndexSearcher indexSearcher; @Override protected void doSetupDerived() throws CorruptIndexException, IOException { this.indexSearcher = new HBaseIndexSearcher(this.indexReader); } @Override protected void doInitDocs() throws CorruptIndexException, IOException { for (int i = 100; i >= 0; --i) { Document doc = this.getDocument(i); indexWriter.addDocument(doc, new StandardAnalyzer(Version.LUCENE_30)); } } private Document getDocument(int i) { Document doc = new Document(); doc.add(new Field("id", "doc" + i, Field.Store.YES, Field.Index.NO)); int randomIndex = (int) (Math.random() * 7.0f); doc.add(new Field("airport", AIRPORTS[randomIndex], Field.Store.NO, Field.Index.ANALYZED_NO_NORMS)); doc.add(new Field("searchterm", Math.random() > 0.5f ? "always" : "never", Field.Store.NO, Field.Index.ANALYZED_NO_NORMS)); recordRandomIndex(100 - i, randomIndex); return doc; } private void recordRandomIndex(final int docIndex, final int airportIndex) { List<Integer> docs = airportMap.get(AIRPORTS[airportIndex]); if (docs == null) { docs = new LinkedList<Integer>(); airportMap.put(AIRPORTS[airportIndex], docs); } docs.add(docIndex); } @Test public void testSortFieldAsc() throws IOException { LOG.info(this.airportMap.toString()); TermQuery termQuery = new TermQuery(new Term("searchterm", "always")); Sort sort = new Sort(new SortField("airport", SortField.STRING)); TopDocs docs = this.indexSearcher.search(termQuery .createWeight(indexSearcher), null, 25, sort, false); LOG.info("Total results are " + docs.scoreDocs.length); this.printScoreDocs(docs.scoreDocs, "Sorted "); assertSortOrderAsc(docs.scoreDocs); } @Test public void testSortFieldDesc() throws IOException { LOG.info(this.airportMap.toString()); TermQuery termQuery = new TermQuery(new Term("searchterm", "always")); Sort sort = new Sort(new SortField("airport", SortField.STRING, true)); //sort by reverse TopDocs docs = this.indexSearcher.search(termQuery .createWeight(indexSearcher), null, 25, sort, false); LOG.info("Total results are " + docs.scoreDocs.length); this.printScoreDocs(docs.scoreDocs, "Sorted "); assertSortOrderDesc(docs.scoreDocs); } @Test(enabled = false) public void testNonExistentSortField() throws IOException { LOG.info(this.airportMap.toString()); IndexSearcher searcher = new IndexSearcher(this.indexReader); try { TopDocs docs = searcher.search(new TermQuery(new Term("searchterm", "always")), 90); LOG.info("Total results are " + docs.scoreDocs.length); this.printScoreDocs(docs.scoreDocs, "Original Order "); // ScoreDoc[] result = this.metaReader.sort(docs.scoreDocs, "airport1"); // TODO: This method should throw an exception for an invalid field to be // sorted. } finally { searcher.close(); } } void printScoreDocs(final ScoreDoc[] scoreDocs, final String prefix) { List<Integer> originalOrder = new ArrayList<Integer>(); for (ScoreDoc scoreDoc : scoreDocs) { originalOrder.add(scoreDoc.doc); } LOG.info(prefix + " is " + originalOrder); } void assertSortOrderAsc(final ScoreDoc[] result) { Map<Integer, String> reverseMap = new HashMap<Integer, String>(); for (final Map.Entry<String, List<Integer>> entry : this.airportMap .entrySet()) { for (final Integer docId : entry.getValue()) { reverseMap.put(docId, entry.getKey()); } } String previousAirport = "000"; for (final ScoreDoc scoreDoc : result) { String currentAirport = reverseMap.get(scoreDoc.doc); Assert.assertTrue(currentAirport + " vs " + previousAirport, currentAirport.compareTo(previousAirport) >= 0); previousAirport = currentAirport; } } void assertSortOrderDesc(final ScoreDoc[] result) { Map<Integer, String> reverseMap = new HashMap<Integer, String>(); for (final Map.Entry<String, List<Integer>> entry : this.airportMap .entrySet()) { for (final Integer docId : entry.getValue()) { reverseMap.put(docId, entry.getKey()); } } String previousAirport = "zzz"; for (final ScoreDoc scoreDoc : result) { String currentAirport = reverseMap.get(scoreDoc.doc); Assert.assertTrue(currentAirport + " vs " + previousAirport, currentAirport.compareTo(previousAirport) <= 0); previousAirport = currentAirport; } } }
src/test/java/com/hbasene/index/search/TestHBaseIndexSearcher.java
/** * Copyright 2010 Karthik Kumar * * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hbasene.index.search; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.apache.log4j.Logger; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.util.Version; import org.testng.annotations.Test; import com.hbasene.index.AbstractHBaseneTest; import com.hbasene.index.search.HBaseIndexSearcher; public class TestHBaseIndexSearcher extends AbstractHBaseneTest { private static final Logger LOG = Logger .getLogger(TestHBaseIndexSearcher.class.getName()); private static final String[] AIRPORTS = { "NYC", "JFK", "EWR", "SEA", "SFO", "OAK", "SJC" }; private final Map<String, List<Integer>> airportMap = new HashMap<String, List<Integer>>(); private HBaseIndexSearcher indexSearcher; @Override protected void doSetupDerived() throws CorruptIndexException, IOException { this.indexSearcher = new HBaseIndexSearcher(this.indexReader); } @Override protected void doInitDocs() throws CorruptIndexException, IOException { for (int i = 100; i >= 0; --i) { Document doc = this.getDocument(i); indexWriter.addDocument(doc, new StandardAnalyzer(Version.LUCENE_30)); } } private Document getDocument(int i) { Document doc = new Document(); doc.add(new Field("id", "doc" + i, Field.Store.YES, Field.Index.NO)); int randomIndex = (int) (Math.random() * 7.0f); doc.add(new Field("airport", AIRPORTS[randomIndex], Field.Store.NO, Field.Index.ANALYZED_NO_NORMS)); doc.add(new Field("searchterm", Math.random() > 0.5f ? "always" : "never", Field.Store.NO, Field.Index.ANALYZED_NO_NORMS)); recordRandomIndex(100 - i, randomIndex); return doc; } private void recordRandomIndex(final int docIndex, final int airportIndex) { List<Integer> docs = airportMap.get(AIRPORTS[airportIndex]); if (docs == null) { docs = new LinkedList<Integer>(); airportMap.put(AIRPORTS[airportIndex], docs); } docs.add(docIndex); } @Test public void testSortField() throws IOException { LOG.info(this.airportMap.toString()); TermQuery termQuery = new TermQuery(new Term("searchterm", "always")); Sort sort = new Sort(new SortField("airport", SortField.STRING)); TopDocs docs = this.indexSearcher.search(termQuery .createWeight(indexSearcher), null, 25, sort, false); LOG.info("Total results are " + docs.scoreDocs.length); this.printScoreDocs(docs.scoreDocs, "Sorted "); assertSortOrder(docs.scoreDocs); } @Test(enabled = false) public void testNonExistentSortField() throws IOException { LOG.info(this.airportMap.toString()); IndexSearcher searcher = new IndexSearcher(this.indexReader); try { TopDocs docs = searcher.search(new TermQuery(new Term("searchterm", "always")), 90); LOG.info("Total results are " + docs.scoreDocs.length); this.printScoreDocs(docs.scoreDocs, "Original Order "); // ScoreDoc[] result = this.metaReader.sort(docs.scoreDocs, "airport1"); // TODO: This method should throw an exception for an invalid field to be // sorted. } finally { searcher.close(); } } void printScoreDocs(final ScoreDoc[] scoreDocs, final String prefix) { List<Integer> originalOrder = new ArrayList<Integer>(); for (ScoreDoc scoreDoc : scoreDocs) { originalOrder.add(scoreDoc.doc); } LOG.info(prefix + " is " + originalOrder); } void assertSortOrder(final ScoreDoc[] result) { Map<Integer, String> reverseMap = new HashMap<Integer, String>(); for (final Map.Entry<String, List<Integer>> entry : this.airportMap .entrySet()) { for (final Integer docId : entry.getValue()) { reverseMap.put(docId, entry.getKey()); } } String previousAirport = "000"; for (final ScoreDoc scoreDoc : result) { String currentAirport = reverseMap.get(scoreDoc.doc); Assert.assertTrue(currentAirport + " vs " + previousAirport, currentAirport.compareTo(previousAirport) >= 0); previousAirport = currentAirport; } } }
test case for descending order as well
src/test/java/com/hbasene/index/search/TestHBaseIndexSearcher.java
test case for descending order as well
Java
apache-2.0
844ba5fcef0080e814b8a2c279cb5ef2fb1155dd
0
Rajith90/carbon-apimgt,uvindra/carbon-apimgt,ruks/carbon-apimgt,bhathiya/carbon-apimgt,chamilaadhi/carbon-apimgt,bhathiya/carbon-apimgt,tharikaGitHub/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,malinthaprasan/carbon-apimgt,tharikaGitHub/carbon-apimgt,chamindias/carbon-apimgt,chamindias/carbon-apimgt,malinthaprasan/carbon-apimgt,wso2/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,wso2/carbon-apimgt,malinthaprasan/carbon-apimgt,uvindra/carbon-apimgt,isharac/carbon-apimgt,fazlan-nazeem/carbon-apimgt,isharac/carbon-apimgt,bhathiya/carbon-apimgt,chamindias/carbon-apimgt,praminda/carbon-apimgt,tharindu1st/carbon-apimgt,wso2/carbon-apimgt,ruks/carbon-apimgt,fazlan-nazeem/carbon-apimgt,prasa7/carbon-apimgt,chamilaadhi/carbon-apimgt,uvindra/carbon-apimgt,fazlan-nazeem/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,uvindra/carbon-apimgt,chamilaadhi/carbon-apimgt,tharindu1st/carbon-apimgt,bhathiya/carbon-apimgt,chamilaadhi/carbon-apimgt,wso2/carbon-apimgt,tharikaGitHub/carbon-apimgt,tharindu1st/carbon-apimgt,Rajith90/carbon-apimgt,ruks/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,praminda/carbon-apimgt,isharac/carbon-apimgt,fazlan-nazeem/carbon-apimgt,tharindu1st/carbon-apimgt,praminda/carbon-apimgt,Rajith90/carbon-apimgt,chamindias/carbon-apimgt,tharikaGitHub/carbon-apimgt,prasa7/carbon-apimgt,prasa7/carbon-apimgt,malinthaprasan/carbon-apimgt,prasa7/carbon-apimgt,ruks/carbon-apimgt,isharac/carbon-apimgt,Rajith90/carbon-apimgt
/* * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.apimgt.persistence.utils; import static org.mockito.Matchers.anyString; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.namespace.QName; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APICategory; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.api.model.APIProductIdentifier; import org.wso2.carbon.apimgt.api.model.Identifier; import org.wso2.carbon.apimgt.api.model.Label; import org.wso2.carbon.apimgt.api.model.Tier; import org.wso2.carbon.apimgt.api.model.URITemplate; import org.wso2.carbon.apimgt.persistence.APIConstants; import org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI; import org.wso2.carbon.apimgt.persistence.dto.PublisherAPI; import org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException; import org.wso2.carbon.apimgt.persistence.internal.ServiceReferenceHolder; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.governance.api.exception.GovernanceException; import org.wso2.carbon.governance.api.generic.GenericArtifactManager; import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact; import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifactImpl; import org.wso2.carbon.governance.api.util.GovernanceArtifactConfiguration; import org.wso2.carbon.governance.api.util.GovernanceUtils; import org.wso2.carbon.registry.core.Association; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.ResourceImpl; import org.wso2.carbon.registry.core.Tag; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import junit.framework.Assert; @RunWith(PowerMockRunner.class) @PrepareForTest({ MultitenantUtils.class, ServiceReferenceHolder.class, GenericArtifact.class, PrivilegedCarbonContext.class, GovernanceUtils.class, ServerConfiguration.class }) public class RegistryPersistenceUtilTestCase { private final int SUPER_TENANT_ID = -1234; private final String SUPER_TENANT_DOMAIN = "carbon.super"; private final int TENANT_ID = 1; private final String TENANT_DOMAIN = "wso2.com"; private Registry registry; @Before public void setupClass() throws Exception { System.setProperty("carbon.home", ""); ServiceReferenceHolder serviceRefHolder = Mockito.mock(ServiceReferenceHolder.class); PowerMockito.mockStatic(ServiceReferenceHolder.class); PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceRefHolder); RealmService realmService = Mockito.mock(RealmService.class); PowerMockito.when(serviceRefHolder.getRealmService()).thenReturn(realmService); TenantManager tenantManager = Mockito.mock(TenantManager.class); PowerMockito.when(realmService.getTenantManager()).thenReturn(tenantManager); PowerMockito.when(tenantManager.getTenantId(SUPER_TENANT_DOMAIN)).thenReturn(SUPER_TENANT_ID); registry = Mockito.mock(Registry.class); PowerMockito.mockStatic(MultitenantUtils.class); Resource resource = new ResourceImpl(); Mockito.when(registry.get(anyString())).thenReturn(resource); Tag[] tags = new Tag[1]; Tag tag = new Tag(); tag.setTagName("testTag"); tags[0] = tag; Mockito.when(registry.getTags(anyString())).thenReturn(tags); PowerMockito.mockStatic(GovernanceUtils.class); PowerMockito.mockStatic(PrivilegedCarbonContext.class); PrivilegedCarbonContext privilegedContext = Mockito.mock(PrivilegedCarbonContext.class); PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedContext); } @Test public void testAPIGet() throws APIManagementException, RegistryException, UserStoreException { GenericArtifact artifact = PersistenceHelper.getSampleAPIArtifact(); API api = RegistryPersistenceUtil.getAPI(artifact, registry); Assert.assertEquals("Attibute overview_type does not match", artifact.getAttribute("overview_type"), api.getType()); Assert.assertEquals("API id does not match", artifact.getId(), api.getUuid()); Assert.assertEquals("API tag does not match", "testTag", api.getTags().iterator().next()); } @Test public void testcreateAPIArtifactContent() throws APIPersistenceException, APIManagementException, RegistryException { API api = new API(new APIIdentifier("pubuser", "TestAPI", "1.0")); Set<Tier> availableTiers = new HashSet<Tier>(); availableTiers.add(new Tier("Unlimited")); availableTiers.add(new Tier("Gold")); api.setAvailableTiers(availableTiers); Set<URITemplate> uriTemplates = new HashSet<URITemplate>(); URITemplate template = new URITemplate(); template.setHTTPVerb("GET"); template.setUriTemplate("/test"); template.setAuthType("None"); uriTemplates.add(template); api.setUriTemplates(uriTemplates); List<APICategory> categories = new ArrayList<APICategory>(); APICategory category = new APICategory(); category.setName("testcategory"); categories.add(category); api.setApiCategories(categories); List<Label> gatewayLabels = new ArrayList<Label>(); Label label = new Label(); label.setName("TestLabel"); gatewayLabels.add(label); api.setGatewayLabels(gatewayLabels); GenericArtifact genericArtifact = new GenericArtifactImpl(new QName("", "TestAPI", ""), "application/vnd.wso2-api+xml"); genericArtifact.setAttribute("URITemplate", "/test"); GenericArtifact retArtifact = RegistryPersistenceUtil.createAPIArtifactContent(genericArtifact, api); Assert.assertEquals("API name does not match", api.getId().getApiName(), retArtifact.getAttribute("overview_name")); Assert.assertEquals("API version does not match", api.getId().getVersion(), retArtifact.getAttribute("overview_version")); Assert.assertEquals("API provider does not match", api.getId().getProviderName(), retArtifact.getAttribute("overview_provider")); } @Test public void testAPIProductGet() throws GovernanceException, APIManagementException { GenericArtifact artifact = PersistenceHelper.getSampleAPIProductArtifact(); APIProduct apiProduct = RegistryPersistenceUtil.getAPIProduct(artifact, registry); Assert.assertEquals("Attibute overview_type does not match", artifact.getAttribute("overview_type"), apiProduct.getType()); Assert.assertEquals("API product id does not match", artifact.getId(), apiProduct.getUuid()); } @Test public void testcreateAPIProductArtifactContent() throws APIPersistenceException, APIManagementException, RegistryException { APIProduct product = new APIProduct(new APIProductIdentifier("pubuser", "TestAPIProd", "1.0.0")); GenericArtifact genericArtifact = new GenericArtifactImpl(new QName("", "TestAPIProd", ""), "application/vnd.wso2-api+xml"); List<APICategory> categories = new ArrayList<APICategory>(); APICategory category = new APICategory(); category.setName("testcategory"); categories.add(category); product.setApiCategories(categories); Set<Tier> availableTiers = new HashSet<Tier>(); availableTiers.add(new Tier("Unlimited")); availableTiers.add(new Tier("Gold")); product.setAvailableTiers(availableTiers); GenericArtifact retArtifact = RegistryPersistenceUtil.createAPIProductArtifactContent(genericArtifact, product); Assert.assertEquals("API name does not match", product.getId().getName(), retArtifact.getAttribute("overview_name")); Assert.assertEquals("API version does not match", product.getId().getVersion(), retArtifact.getAttribute("overview_version")); Assert.assertEquals("API provider does not match", product.getId().getProviderName(), retArtifact.getAttribute("overview_provider")); } @Test public void testGetAPIForSearch() throws APIPersistenceException, GovernanceException { GenericArtifact genericArtifact = PersistenceHelper.getSampleAPIArtifact(); PublisherAPI api = RegistryPersistenceUtil.getAPIForSearch(genericArtifact); Assert.assertEquals("API name does not match", genericArtifact.getAttribute("overview_name"), api.getApiName()); Assert.assertEquals("API version does not match", genericArtifact.getAttribute("overview_version"), api.getVersion()); Assert.assertEquals("API provider does not match", genericArtifact.getAttribute("overview_provider"), api.getProviderName()); } @Test public void testGetDevPortalAPIForSearch() throws APIPersistenceException, GovernanceException { GenericArtifact genericArtifact = PersistenceHelper.getSampleAPIArtifact(); DevPortalAPI api = RegistryPersistenceUtil.getDevPortalAPIForSearch(genericArtifact); Assert.assertEquals("API name does not match", genericArtifact.getAttribute("overview_name"), api.getApiName()); Assert.assertEquals("API version does not match", genericArtifact.getAttribute("overview_version"), api.getVersion()); Assert.assertEquals("API provider does not match", genericArtifact.getAttribute("overview_provider"), api.getProviderName()); } @Test public void testTenantDomain() { PowerMockito.mockStatic(ServerConfiguration.class); ServerConfiguration config = Mockito.mock(ServerConfiguration.class); PowerMockito.when(ServerConfiguration.getInstance()).thenReturn(config); PowerMockito.when(config.getFirstProperty(anyString())).thenReturn(null); String domain = RegistryPersistenceUtil .getTenantDomain(new APIIdentifier("test@" + TENANT_DOMAIN, "test", "1.0")); domain = RegistryPersistenceUtil .getTenantDomain(new APIIdentifier("test", "test", "1.0")); } @Test public void testGetArtifactManager() throws RegistryException, APIPersistenceException { Registry registry = Mockito.mock(UserRegistry.class); GovernanceArtifactConfiguration conf = Mockito.mock(GovernanceArtifactConfiguration.class); PowerMockito.when(GovernanceUtils.findGovernanceArtifactConfiguration(APIConstants.API_KEY, registry)) .thenReturn(conf); Association[] assosiations = new Association[0]; Mockito.when(conf.getRelationshipDefinitions()).thenReturn(assosiations ); GenericArtifactManager manager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY); Assert.assertNotNull("Manager is null", manager); } }
components/apimgt/org.wso2.carbon.apimgt.persistence/src/test/java/org/wso2/carbon/apimgt/persistence/utils/RegistryPersistenceUtilTestCase.java
/* * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.apimgt.persistence.utils; import static org.mockito.Matchers.anyString; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.namespace.QName; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APICategory; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.api.model.APIProductIdentifier; import org.wso2.carbon.apimgt.api.model.Identifier; import org.wso2.carbon.apimgt.api.model.Label; import org.wso2.carbon.apimgt.api.model.Tier; import org.wso2.carbon.apimgt.api.model.URITemplate; import org.wso2.carbon.apimgt.persistence.APIConstants; import org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI; import org.wso2.carbon.apimgt.persistence.dto.PublisherAPI; import org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException; import org.wso2.carbon.apimgt.persistence.internal.ServiceReferenceHolder; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.governance.api.exception.GovernanceException; import org.wso2.carbon.governance.api.generic.GenericArtifactManager; import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact; import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifactImpl; import org.wso2.carbon.governance.api.util.GovernanceArtifactConfiguration; import org.wso2.carbon.governance.api.util.GovernanceUtils; import org.wso2.carbon.registry.core.Association; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.ResourceImpl; import org.wso2.carbon.registry.core.Tag; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import junit.framework.Assert; @RunWith(PowerMockRunner.class) @PrepareForTest({ MultitenantUtils.class, ServiceReferenceHolder.class, GenericArtifact.class, PrivilegedCarbonContext.class, GovernanceUtils.class, ServerConfiguration.class }) public class RegistryPersistenceUtilTestCase { private final int SUPER_TENANT_ID = -1234; private final String SUPER_TENANT_DOMAIN = "carbon.super"; private final int TENANT_ID = 1; private final String TENANT_DOMAIN = "wso2.com"; private Registry registry; @Before public void setupClass() throws Exception { System.setProperty("carbon.home", ""); ServiceReferenceHolder serviceRefHolder = Mockito.mock(ServiceReferenceHolder.class); PowerMockito.mockStatic(ServiceReferenceHolder.class); PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceRefHolder); RealmService realmService = Mockito.mock(RealmService.class); PowerMockito.when(serviceRefHolder.getRealmService()).thenReturn(realmService); TenantManager tenantManager = Mockito.mock(TenantManager.class); PowerMockito.when(realmService.getTenantManager()).thenReturn(tenantManager); PowerMockito.when(tenantManager.getTenantId(SUPER_TENANT_DOMAIN)).thenReturn(SUPER_TENANT_ID); registry = Mockito.mock(Registry.class); PowerMockito.mockStatic(MultitenantUtils.class); Resource resource = new ResourceImpl(); Mockito.when(registry.get(anyString())).thenReturn(resource); Tag[] tags = new Tag[1]; Tag tag = new Tag(); tag.setTagName("testTag"); tags[0] = tag; Mockito.when(registry.getTags(anyString())).thenReturn(tags); PowerMockito.mockStatic(GovernanceUtils.class); PowerMockito.mockStatic(PrivilegedCarbonContext.class); PrivilegedCarbonContext privilegedContext = Mockito.mock(PrivilegedCarbonContext.class); PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedContext); } @Test public void testAPIGet() throws APIManagementException, RegistryException, UserStoreException { GenericArtifact artifact = PersistenceHelper.getSampleAPIArtifact(); API api = RegistryPersistenceUtil.getAPI(artifact, registry); Assert.assertEquals("Attibute overview_type does not match", artifact.getAttribute("overview_type"), api.getType()); Assert.assertEquals("API id does not match", artifact.getId(), api.getUuid()); Assert.assertEquals("API tag does not match", "testTag", api.getTags().iterator().next()); } @Test public void testcreateAPIArtifactContent() throws APIPersistenceException, APIManagementException, RegistryException { API api = new API(new APIIdentifier("pubuser", "TestAPI", "1.0")); Set<Tier> availableTiers = new HashSet<Tier>(); availableTiers.add(new Tier("Unlimited")); availableTiers.add(new Tier("Gold")); api.setAvailableTiers(availableTiers); Set<URITemplate> uriTemplates = new HashSet<URITemplate>(); URITemplate template = new URITemplate(); template.setHTTPVerb("GET"); template.setUriTemplate("/test"); template.setAuthType("None"); uriTemplates.add(template); api.setUriTemplates(uriTemplates); List<APICategory> categories = new ArrayList<APICategory>(); APICategory category = new APICategory(); category.setName("testcategory"); categories.add(category); api.setApiCategories(categories); List<Label> gatewayLabels = new ArrayList<Label>(); Label label = new Label(); label.setName("TestLabel"); gatewayLabels.add(label); api.setGatewayLabels(gatewayLabels); GenericArtifact genericArtifact = new GenericArtifactImpl(new QName("", "TestAPI", ""), "application/vnd.wso2-api+xml"); genericArtifact.setAttribute("URITemplate", "/test"); GenericArtifact retArtifact = RegistryPersistenceUtil.createAPIArtifactContent(genericArtifact, api); Assert.assertEquals("API name does not match", api.getId().getApiName(), retArtifact.getAttribute("overview_name")); Assert.assertEquals("API version does not match", api.getId().getVersion(), retArtifact.getAttribute("overview_version")); Assert.assertEquals("API provider does not match", api.getId().getProviderName(), retArtifact.getAttribute("overview_provider")); } @Test public void testAPIProductGet() throws GovernanceException, APIManagementException { GenericArtifact artifact = PersistenceHelper.getSampleAPIProductArtifact(); APIProduct apiProduct = RegistryPersistenceUtil.getAPIProduct(artifact, registry); Assert.assertEquals("Attibute overview_type does not match", artifact.getAttribute("overview_type"), apiProduct.getType()); Assert.assertEquals("API product id does not match", artifact.getId(), apiProduct.getUuid()); } @Test public void testcreateAPIProductArtifactContent() throws APIPersistenceException, APIManagementException, RegistryException { APIProduct product = new APIProduct(new APIProductIdentifier("pubuser", "TestAPIProd", "1.0.0")); GenericArtifact genericArtifact = new GenericArtifactImpl(new QName("", "TestAPIProd", ""), "application/vnd.wso2-api+xml"); List<APICategory> categories = new ArrayList<APICategory>(); APICategory category = new APICategory(); category.setName("testcategory"); categories.add(category); product.setApiCategories(categories); Set<Tier> availableTiers = new HashSet<Tier>(); availableTiers.add(new Tier("Unlimited")); availableTiers.add(new Tier("Gold")); product.setAvailableTiers(availableTiers); GenericArtifact retArtifact = RegistryPersistenceUtil.createAPIProductArtifactContent(genericArtifact, product); Assert.assertEquals("API name does not match", product.getId().getName(), retArtifact.getAttribute("overview_name")); Assert.assertEquals("API version does not match", product.getId().getVersion(), retArtifact.getAttribute("overview_version")); Assert.assertEquals("API provider does not match", product.getId().getProviderName(), retArtifact.getAttribute("overview_provider")); } @Test public void testGetAPIForSearch() throws APIPersistenceException, GovernanceException { GenericArtifact genericArtifact = PersistenceHelper.getSampleAPIArtifact(); PublisherAPI api = RegistryPersistenceUtil.getAPIForSearch(genericArtifact); Assert.assertEquals("API name does not match", genericArtifact.getAttribute("overview_name"), api.getApiName()); Assert.assertEquals("API version does not match", genericArtifact.getAttribute("overview_version"), api.getVersion()); Assert.assertEquals("API provider does not match", genericArtifact.getAttribute("overview_provider"), api.getProviderName()); } @Test public void testGetDevPortalAPIForSearch() throws APIPersistenceException, GovernanceException { GenericArtifact genericArtifact = PersistenceHelper.getSampleAPIArtifact(); DevPortalAPI api = RegistryPersistenceUtil.getDevPortalAPIForSearch(genericArtifact); Assert.assertEquals("API name does not match", genericArtifact.getAttribute("overview_name"), api.getApiName()); Assert.assertEquals("API version does not match", genericArtifact.getAttribute("overview_version"), api.getVersion()); Assert.assertEquals("API provider does not match", genericArtifact.getAttribute("overview_provider"), api.getProviderName()); } @Test public void testTenantDomain() { PowerMockito.mockStatic(ServerConfiguration.class); ServerConfiguration config = Mockito.mock(ServerConfiguration.class); PowerMockito.when(ServerConfiguration.getInstance()).thenReturn(config); PowerMockito.when(config.getFirstProperty(anyString())).thenReturn(null); String domain = RegistryPersistenceUtil .getTenantDomain(new APIIdentifier("test@" + TENANT_DOMAIN, "test", "1.0")); //Assert.assertEquals("Tenant domain does not match", TENANT_DOMAIN, domain); domain = RegistryPersistenceUtil .getTenantDomain(new APIIdentifier("test", "test", "1.0")); //Assert.assertEquals("Super tenant domain does not match", SUPER_TENANT_DOMAIN, domain); } @Test public void testGetArtifactManager() throws RegistryException, APIPersistenceException { Registry registry = Mockito.mock(UserRegistry.class); GovernanceArtifactConfiguration conf = Mockito.mock(GovernanceArtifactConfiguration.class); PowerMockito.when(GovernanceUtils.findGovernanceArtifactConfiguration(APIConstants.API_KEY, registry)) .thenReturn(conf); Association[] assosiations = new Association[0]; Mockito.when(conf.getRelationshipDefinitions()).thenReturn(assosiations ); GenericArtifactManager manager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY); Assert.assertNotNull("Manager is null", manager); } }
add review comment
components/apimgt/org.wso2.carbon.apimgt.persistence/src/test/java/org/wso2/carbon/apimgt/persistence/utils/RegistryPersistenceUtilTestCase.java
add review comment
Java
bsd-3-clause
e3b603a5ea7055c80c13eded990e0140e3fe36d4
0
wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy
/* * Copyright (c) 2013, 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. * * 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.oracle.graal.truffle.test; import java.util.*; import org.junit.*; import com.oracle.graal.api.code.*; import com.oracle.graal.compiler.test.*; import com.oracle.graal.debug.*; import com.oracle.graal.debug.Debug.Scope; import com.oracle.graal.java.*; import com.oracle.graal.loop.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.java.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.phases.*; import com.oracle.graal.phases.common.*; import com.oracle.graal.phases.tiers.*; import com.oracle.graal.printer.*; import com.oracle.graal.truffle.*; import com.oracle.graal.virtual.phases.ea.*; import com.oracle.truffle.api.*; import com.oracle.truffle.api.nodes.*; public class PartialEvaluationTest extends GraalCompilerTest { private static final long UNROLL_LIMIT = 100; private final TruffleCompilerImpl truffleCompiler; public PartialEvaluationTest() { // Make sure Truffle runtime is initialized. Assert.assertTrue(Truffle.getRuntime() != null); this.truffleCompiler = new TruffleCompilerImpl(); DebugEnvironment.initialize(System.out); } protected InstalledCode assertPartialEvalEquals(String methodName, RootNode root) { return assertPartialEvalEquals(methodName, root, new Object[0]); } protected InstalledCode assertPartialEvalEquals(String methodName, RootNode root, Object[] arguments) { Assumptions assumptions = new Assumptions(true); StructuredGraph actual = partialEval(root, arguments, assumptions, true); InstalledCode result = new InstalledCode(); truffleCompiler.compileMethodHelper(actual, assumptions, root.toString(), getSpeculationLog(), result); StructuredGraph expected = parseForComparison(methodName); removeFrameStates(actual); Assert.assertEquals(getCanonicalGraphString(expected, true, true), getCanonicalGraphString(actual, true, true)); return result; } protected void assertPartialEvalNoInvokes(RootNode root) { assertPartialEvalNoInvokes(root, new Object[0]); } protected void assertPartialEvalNoInvokes(RootNode root, Object[] arguments) { Assumptions assumptions = new Assumptions(true); StructuredGraph actual = partialEval(root, arguments, assumptions, true); removeFrameStates(actual); for (MethodCallTargetNode node : actual.getNodes(MethodCallTargetNode.class)) { Assert.fail("Found invalid method call target node: " + node); } } protected StructuredGraph partialEval(RootNode root, Object[] arguments, final Assumptions assumptions, final boolean canonicalizeReads) { final OptimizedCallTarget compilable = (OptimizedCallTarget) Truffle.getRuntime().createCallTarget(root); // Executed AST so that all classes are loaded and initialized. compilable.call(arguments); compilable.call(arguments); compilable.call(arguments); compilable.performInlining(); try (Scope s = Debug.scope("TruffleCompilation", new TruffleDebugJavaMethod(compilable))) { StructuredGraph resultGraph = truffleCompiler.getPartialEvaluator().createGraph(compilable, assumptions); CanonicalizerPhase canonicalizer = new CanonicalizerPhase(canonicalizeReads); PhaseContext context = new PhaseContext(getProviders(), assumptions); if (resultGraph.hasLoops()) { boolean unrolled; do { unrolled = false; LoopsData loopsData = new LoopsData(resultGraph); loopsData.detectedCountedLoops(); for (LoopEx ex : innerLoopsFirst(loopsData.countedLoops())) { if (ex.counted().isConstantMaxTripCount()) { long constant = ex.counted().constantMaxTripCount(); if (constant <= UNROLL_LIMIT) { LoopTransformations.fullUnroll(ex, context, canonicalizer); Debug.dump(resultGraph, "After loop unrolling %d times", constant); canonicalizer.apply(resultGraph, context); unrolled = true; break; } } } } while (unrolled); } new DeadCodeEliminationPhase().apply(resultGraph); new PartialEscapePhase(true, canonicalizer).apply(resultGraph, context); return resultGraph; } catch (Throwable e) { throw Debug.handle(e); } } private static List<LoopEx> innerLoopsFirst(Collection<LoopEx> loops) { ArrayList<LoopEx> sortedLoops = new ArrayList<>(loops); Collections.sort(sortedLoops, new Comparator<LoopEx>() { @Override public int compare(LoopEx o1, LoopEx o2) { return o2.lirLoop().depth - o1.lirLoop().depth; } }); return sortedLoops; } protected void removeFrameStates(StructuredGraph graph) { for (FrameState frameState : graph.getNodes(FrameState.class)) { frameState.replaceAtUsages(null); frameState.safeDelete(); } new CanonicalizerPhase(true).apply(graph, new PhaseContext(getProviders(), new Assumptions(false))); new DeadCodeEliminationPhase().apply(graph); } protected StructuredGraph parseForComparison(final String methodName) { try (Scope s = Debug.scope("Truffle", new DebugDumpScope("Comparison: " + methodName))) { Assumptions assumptions = new Assumptions(false); StructuredGraph graph = parse(methodName); PhaseContext context = new PhaseContext(getProviders(), assumptions); CanonicalizerPhase canonicalizer = new CanonicalizerPhase(true); canonicalizer.apply(graph, context); // Additional inlining. PhaseSuite<HighTierContext> graphBuilderSuite = getCustomGraphBuilderSuite(GraphBuilderConfiguration.getEagerInfopointDefault()); graphBuilderSuite.appendPhase(canonicalizer); graphBuilderSuite.appendPhase(new DeadCodeEliminationPhase()); new ConvertDeoptimizeToGuardPhase().apply(graph); canonicalizer.apply(graph, context); new DeadCodeEliminationPhase().apply(graph); HighTierContext highTierContext = new HighTierContext(getProviders(), assumptions, null, graphBuilderSuite, TruffleCompilerImpl.Optimizations); InliningPhase inliningPhase = new InliningPhase(canonicalizer); inliningPhase.apply(graph, highTierContext); removeFrameStates(graph); new ConvertDeoptimizeToGuardPhase().apply(graph); canonicalizer.apply(graph, context); new DeadCodeEliminationPhase().apply(graph); new LoweringPhase(new CanonicalizerPhase(true), LoweringTool.StandardLoweringStage.HIGH_TIER).apply(graph, context); canonicalizer.apply(graph, context); new DeadCodeEliminationPhase().apply(graph); return graph; } catch (Throwable e) { throw Debug.handle(e); } } }
graal/com.oracle.graal.truffle.test/src/com/oracle/graal/truffle/test/PartialEvaluationTest.java
/* * Copyright (c) 2013, 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. * * 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.oracle.graal.truffle.test; import java.util.*; import org.junit.*; import com.oracle.graal.api.code.*; import com.oracle.graal.compiler.test.*; import com.oracle.graal.debug.*; import com.oracle.graal.debug.Debug.Scope; import com.oracle.graal.java.*; import com.oracle.graal.loop.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.java.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.phases.*; import com.oracle.graal.phases.common.*; import com.oracle.graal.phases.tiers.*; import com.oracle.graal.printer.*; import com.oracle.graal.truffle.*; import com.oracle.graal.virtual.phases.ea.*; import com.oracle.truffle.api.*; import com.oracle.truffle.api.nodes.*; public class PartialEvaluationTest extends GraalCompilerTest { private static final long UNROLL_LIMIT = 100; private final TruffleCompilerImpl truffleCompiler; public PartialEvaluationTest() { // Make sure Truffle runtime is initialized. Assert.assertTrue(Truffle.getRuntime() != null); this.truffleCompiler = new TruffleCompilerImpl(); DebugEnvironment.initialize(System.out); } protected InstalledCode assertPartialEvalEquals(String methodName, RootNode root) { return assertPartialEvalEquals(methodName, root, new Object[0]); } protected InstalledCode assertPartialEvalEquals(String methodName, RootNode root, Object[] arguments) { Assumptions assumptions = new Assumptions(true); StructuredGraph actual = partialEval(root, arguments, assumptions, true); InstalledCode result = truffleCompiler.compileMethodHelper(actual, assumptions, root.toString(), getSpeculationLog(), null); StructuredGraph expected = parseForComparison(methodName); removeFrameStates(actual); Assert.assertEquals(getCanonicalGraphString(expected, true, true), getCanonicalGraphString(actual, true, true)); return result; } protected void assertPartialEvalNoInvokes(RootNode root) { assertPartialEvalNoInvokes(root, new Object[0]); } protected void assertPartialEvalNoInvokes(RootNode root, Object[] arguments) { Assumptions assumptions = new Assumptions(true); StructuredGraph actual = partialEval(root, arguments, assumptions, true); removeFrameStates(actual); for (MethodCallTargetNode node : actual.getNodes(MethodCallTargetNode.class)) { Assert.fail("Found invalid method call target node: " + node); } } protected StructuredGraph partialEval(RootNode root, Object[] arguments, final Assumptions assumptions, final boolean canonicalizeReads) { final OptimizedCallTarget compilable = (OptimizedCallTarget) Truffle.getRuntime().createCallTarget(root); // Executed AST so that all classes are loaded and initialized. compilable.call(arguments); compilable.call(arguments); compilable.call(arguments); compilable.performInlining(); try (Scope s = Debug.scope("TruffleCompilation", new TruffleDebugJavaMethod(compilable))) { StructuredGraph resultGraph = truffleCompiler.getPartialEvaluator().createGraph(compilable, assumptions); CanonicalizerPhase canonicalizer = new CanonicalizerPhase(canonicalizeReads); PhaseContext context = new PhaseContext(getProviders(), assumptions); if (resultGraph.hasLoops()) { boolean unrolled; do { unrolled = false; LoopsData loopsData = new LoopsData(resultGraph); loopsData.detectedCountedLoops(); for (LoopEx ex : innerLoopsFirst(loopsData.countedLoops())) { if (ex.counted().isConstantMaxTripCount()) { long constant = ex.counted().constantMaxTripCount(); if (constant <= UNROLL_LIMIT) { LoopTransformations.fullUnroll(ex, context, canonicalizer); Debug.dump(resultGraph, "After loop unrolling %d times", constant); canonicalizer.apply(resultGraph, context); unrolled = true; break; } } } } while (unrolled); } new DeadCodeEliminationPhase().apply(resultGraph); new PartialEscapePhase(true, canonicalizer).apply(resultGraph, context); return resultGraph; } catch (Throwable e) { throw Debug.handle(e); } } private static List<LoopEx> innerLoopsFirst(Collection<LoopEx> loops) { ArrayList<LoopEx> sortedLoops = new ArrayList<>(loops); Collections.sort(sortedLoops, new Comparator<LoopEx>() { @Override public int compare(LoopEx o1, LoopEx o2) { return o2.lirLoop().depth - o1.lirLoop().depth; } }); return sortedLoops; } protected void removeFrameStates(StructuredGraph graph) { for (FrameState frameState : graph.getNodes(FrameState.class)) { frameState.replaceAtUsages(null); frameState.safeDelete(); } new CanonicalizerPhase(true).apply(graph, new PhaseContext(getProviders(), new Assumptions(false))); new DeadCodeEliminationPhase().apply(graph); } protected StructuredGraph parseForComparison(final String methodName) { try (Scope s = Debug.scope("Truffle", new DebugDumpScope("Comparison: " + methodName))) { Assumptions assumptions = new Assumptions(false); StructuredGraph graph = parse(methodName); PhaseContext context = new PhaseContext(getProviders(), assumptions); CanonicalizerPhase canonicalizer = new CanonicalizerPhase(true); canonicalizer.apply(graph, context); // Additional inlining. PhaseSuite<HighTierContext> graphBuilderSuite = getCustomGraphBuilderSuite(GraphBuilderConfiguration.getEagerInfopointDefault()); graphBuilderSuite.appendPhase(canonicalizer); graphBuilderSuite.appendPhase(new DeadCodeEliminationPhase()); new ConvertDeoptimizeToGuardPhase().apply(graph); canonicalizer.apply(graph, context); new DeadCodeEliminationPhase().apply(graph); HighTierContext highTierContext = new HighTierContext(getProviders(), assumptions, null, graphBuilderSuite, TruffleCompilerImpl.Optimizations); InliningPhase inliningPhase = new InliningPhase(canonicalizer); inliningPhase.apply(graph, highTierContext); removeFrameStates(graph); new ConvertDeoptimizeToGuardPhase().apply(graph); canonicalizer.apply(graph, context); new DeadCodeEliminationPhase().apply(graph); new LoweringPhase(new CanonicalizerPhase(true), LoweringTool.StandardLoweringStage.HIGH_TIER).apply(graph, context); canonicalizer.apply(graph, context); new DeadCodeEliminationPhase().apply(graph); return graph; } catch (Throwable e) { throw Debug.handle(e); } } }
Fix partial evaluation test.
graal/com.oracle.graal.truffle.test/src/com/oracle/graal/truffle/test/PartialEvaluationTest.java
Fix partial evaluation test.
Java
bsd-3-clause
1dcaa2098c87751ce28224b6861cfa0babe8313a
0
NCIP/caaers,CBIIT/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,NCIP/caaers
package gov.nih.nci.cabig.caaers.tools; import gov.nih.nci.cabig.caaers.CaaersSystemException; import gov.nih.nci.cabig.caaers.dao.AgentDao; import gov.nih.nci.cabig.caaers.dao.CtcDao; import gov.nih.nci.cabig.caaers.dao.DiseaseTermDao; import gov.nih.nci.cabig.caaers.dao.InvestigationalNewDrugDao; import gov.nih.nci.cabig.caaers.dao.InvestigatorDao; import gov.nih.nci.cabig.caaers.dao.OrganizationDao; import gov.nih.nci.cabig.caaers.dao.StudyDao; import gov.nih.nci.cabig.caaers.dao.query.InvestigatorQuery; import gov.nih.nci.cabig.caaers.domain.AeTerminology; import gov.nih.nci.cabig.caaers.domain.CoordinatingCenter; import gov.nih.nci.cabig.caaers.domain.Ctc; import gov.nih.nci.cabig.caaers.domain.CtepStudyDisease; import gov.nih.nci.cabig.caaers.domain.DiseaseCodeTerm; import gov.nih.nci.cabig.caaers.domain.DiseaseTerminology; import gov.nih.nci.cabig.caaers.domain.FundingSponsor; import gov.nih.nci.cabig.caaers.domain.INDType; import gov.nih.nci.cabig.caaers.domain.Identifier; import gov.nih.nci.cabig.caaers.domain.Investigator; import gov.nih.nci.cabig.caaers.domain.LocalInvestigator; import gov.nih.nci.cabig.caaers.domain.LocalOrganization; import gov.nih.nci.cabig.caaers.domain.LocalStudy; import gov.nih.nci.cabig.caaers.domain.Organization; import gov.nih.nci.cabig.caaers.domain.OrganizationAssignedIdentifier; import gov.nih.nci.cabig.caaers.domain.SiteInvestigator; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyAgent; import gov.nih.nci.cabig.caaers.domain.StudyAgentINDAssociation; import gov.nih.nci.cabig.caaers.domain.StudyCoordinatingCenter; import gov.nih.nci.cabig.caaers.domain.StudyFundingSponsor; import gov.nih.nci.cabig.caaers.domain.StudyInvestigator; import gov.nih.nci.cabig.caaers.domain.StudyOrganization; import gov.nih.nci.cabig.caaers.domain.StudySite; import gov.nih.nci.cabig.caaers.domain.StudyTherapyType; import gov.nih.nci.cabig.caaers.domain.TreatmentAssignment; import gov.nih.nci.cabig.caaers.domain.repository.InvestigatorRepository; import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome; import gov.nih.nci.cabig.caaers.service.StudyImportServiceImpl; import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome.Message; import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome.Severity; import gov.nih.nci.cabig.caaers.utils.DateUtils; import gov.nih.nci.cabig.caaers.validation.validator.DomainObjectValidator; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; public class ExcelProcessor { private POIFSFileSystem poifs; private HSSFWorkbook wb; private HSSFSheet studyInfoSheet; private HSSFSheet agentInfoSheet; private HSSFSheet diseaseInfoSheet; private HSSFSheet tacInfoSheet; private HSSFSheet orgInfoSheet; private HSSFSheet investigatorInfoSheet; private HSSFSheet therapyInfoSheet; // Study related objects private Study study; private OrganizationDao orgdao; private CtcDao ctcdao; private StudyDao studydao; private AgentDao agentdao; private InvestigationalNewDrugDao investigationalnewdrugdao; private DiseaseTermDao diseasetermdao; private InvestigatorDao investigatordao; private InvestigatorRepository investigatorRepository; private StudyImportServiceImpl studyImportService; private String primaryIdentifierString; private String localDocumentNumber; private String studyTitle; private String phaseCode; private DiseaseTerminology diseaseTerminology; private AeTerminology aeTerminology; private DomainObjectImportOutcome<Study> studyImportOutcome; private DomainObjectValidator domainObjectValidator; private int rowCount = 0; private final String STUDY_SHEET_NAME = "admin info"; private final String AGENT_SHEET_NAME = "agent info"; private final String DISEASE_SHEET_NAME = "disease info"; private final String TAC_SHEET_NAME = "TAC info"; private final String ORG_SHEET_NAME = "organizations"; private final String INVESTIGATOR_SHEET_NAME = "investigators"; private final String THERAPY_SHEET_NAME = "therapies"; public ExcelProcessor() { } public void processExcel(File inputFile) throws Exception { bootstrap(inputFile); syncInvestigators(); while (rowCount > 0) { study = new LocalStudy(); initializeStudy(study); setStudyAgents(study); setStudyDiseases(study); setStudyTreatmentAssignments(study); setStudyOrganizations(study); setStudyInvestigators(study); setStudyTherapies(study); validateStudy(study); rowCount--; } System.out.println("Excel Import Complete"); System.out.println(""); System.out.println("Excel Import Summary"); System.out.println("-----------------------------------------------------------"); System.out.println("Total Number of Investigators Processed ---> "+investigatorInfoSheet.getLastRowNum()); System.out.println("Total Number of Studies Processed ---> "+studyInfoSheet.getLastRowNum()); System.out.println("-----------------------------------------------------------"); } private void bootstrap(File inputFile) throws Exception { poifs = new POIFSFileSystem(new FileInputStream(inputFile)); // create a workbook out of the input stream wb = new HSSFWorkbook(poifs); studyInfoSheet = getSheet(STUDY_SHEET_NAME); agentInfoSheet = getSheet(AGENT_SHEET_NAME); diseaseInfoSheet = getSheet(DISEASE_SHEET_NAME); tacInfoSheet = getSheet(TAC_SHEET_NAME); orgInfoSheet = getSheet(ORG_SHEET_NAME); investigatorInfoSheet = getSheet(INVESTIGATOR_SHEET_NAME); therapyInfoSheet = getSheet(THERAPY_SHEET_NAME); rowCount = studyInfoSheet.getLastRowNum(); } private void initializeStudy(Study study) { primaryIdentifierString = getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet.getRow(rowCount).getCell((short) 0)); localDocumentNumber = getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet.getRow(rowCount).getCell((short) 1)); studyTitle = getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet .getRow(rowCount).getCell((short) 2)); phaseCode = getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet .getRow(rowCount).getCell((short) 3)); FundingSponsor fs = new FundingSponsor(); StudyFundingSponsor sfs = new StudyFundingSponsor(); Organization fo = new LocalOrganization(); fo.setName("Cancer Therapy Evaluation Program"); sfs.setOrganization(fo); fs.setStudyFundingSponsor(sfs); OrganizationAssignedIdentifier sfi = new OrganizationAssignedIdentifier(); sfi.setValue(getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet .getRow(rowCount).getCell((short) 0))); sfi.setPrimaryIndicator(true); fs.setOrganizationAssignedIdentifier(sfi); study.setFundingSponsor(fs); //study.setShortTitle(localDocumentNumber); study.setShortTitle(studyTitle); study.setLongTitle(studyTitle); aeTerminology = study.getAeTerminology(); Ctc ctc = new Ctc(); ctc.setName(getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet .getRow(rowCount).getCell((short) 4))); aeTerminology.setCtcVersion(ctc); study.setAeTerminology(aeTerminology); study.setDescription(studyTitle); diseaseTerminology = study.getDiseaseTerminology(); diseaseTerminology.setDiseaseCodeTerm(DiseaseCodeTerm.getByCode(1)); study.setDiseaseTerminology(diseaseTerminology); study.setMultiInstitutionIndicator(true); study.setStatus(gov.nih.nci.cabig.caaers.domain.Study.STATUS_ACTIVE); study.setAdeersReporting(Boolean.TRUE); if("I".equals(phaseCode)){ study.setPhaseCode("Phase I Trial"); } if("II".equals(phaseCode)){ study.setPhaseCode("Phase II Trial"); } if("I/II".equals(phaseCode)){ study.setPhaseCode("Phase I/II Trial"); } if("III".equals(phaseCode)){ study.setPhaseCode("Phase III Trial"); } if("II/III".equals(phaseCode)){ study.setPhaseCode("Phase II/III Trial"); } if("IV".equals(phaseCode)){ study.setPhaseCode("Phase IV Trial"); } if("0".equals(phaseCode)){ study.setPhaseCode("Phase 0 Trial"); } if("Pilot".equals(phaseCode)){ study.setPhaseCode("Pilot"); } } private void setStudyAgents(Study study) { int agentRows = agentInfoSheet.getLastRowNum(); List<StudyAgent> studyAgents = new ArrayList<StudyAgent>(); StudyAgent studyAgent = null; INDType indType; String indNumber; List<StudyAgentINDAssociation> studyAgentINDAssociations; StudyAgentINDAssociation studyAgentINDAssociation; for (int agentRow = 1; agentRow <= agentRows; agentRow++) { if (primaryIdentifierString.equalsIgnoreCase(getCellData( AGENT_SHEET_NAME, agentRow, agentInfoSheet.getRow(agentRow) .getCell((short) 0)))) { studyAgent = new StudyAgent(agentdao .getByNscNumber(getCellData(AGENT_SHEET_NAME, agentRow, agentInfoSheet.getRow(agentRow).getCell( (short) 2)))); studyAgent.setStudy(study); indType = getCellData(AGENT_SHEET_NAME, agentRow, agentInfoSheet.getRow(agentRow).getCell((short) 4)) .equalsIgnoreCase("Investigational") ? INDType.CTEP_IND : INDType.NA_COMMERCIAL; studyAgent.setIndType(indType); studyAgent.setPartOfLeadIND(getCellData(AGENT_SHEET_NAME, agentRow, (agentInfoSheet.getRow(agentRow).getCell((short) 3))) .equalsIgnoreCase("Yes") ? true : false); indNumber = getCellData(AGENT_SHEET_NAME, agentRow, agentInfoSheet.getRow(agentRow).getCell((short) 6)); if (!(indNumber.equalsIgnoreCase("null"))) { studyAgentINDAssociation = new StudyAgentINDAssociation(); studyAgentINDAssociation.setStudyAgent(studyAgent); studyAgentINDAssociation .setInvestigationalNewDrug(investigationalnewdrugdao .fetchCtepInd()); studyAgentINDAssociations = new ArrayList<StudyAgentINDAssociation>(); studyAgentINDAssociations.add(studyAgentINDAssociation); studyAgent .setStudyAgentINDAssociations(studyAgentINDAssociations); } studyAgents.add(studyAgent); } } study.setStudyAgents(studyAgents); } private void setStudyDiseases(Study study) { int diseaseRows = diseaseInfoSheet.getLastRowNum(); List<CtepStudyDisease> ctepStudyDiseases = new ArrayList<CtepStudyDisease>(); CtepStudyDisease ctepStudyDisease = null; String diseaseTermString = null; boolean leadDisease; for (int diseaseRow = 1; diseaseRow <= diseaseRows; diseaseRow++) { if (primaryIdentifierString.equalsIgnoreCase(getCellData( DISEASE_SHEET_NAME, diseaseRow, diseaseInfoSheet.getRow( diseaseRow).getCell((short) 0)))) { diseaseTermString = getCellData(DISEASE_SHEET_NAME, diseaseRow, diseaseInfoSheet.getRow(diseaseRow).getCell((short) 1)); ctepStudyDisease = new CtepStudyDisease(); ctepStudyDisease.setDiseaseTerm(diseasetermdao .getByCTEPTermName(diseaseTermString)); leadDisease = getCellData(DISEASE_SHEET_NAME, diseaseRow, diseaseInfoSheet.getRow(diseaseRow).getCell((short) 2)) .equalsIgnoreCase("Yes") ? true : false; ctepStudyDisease.setLeadDisease(leadDisease); ctepStudyDiseases.add(ctepStudyDisease); } } study.setCtepStudyDiseases(ctepStudyDiseases); } private void setStudyTreatmentAssignments(Study study) { int tacRows = tacInfoSheet.getLastRowNum(); List<TreatmentAssignment> treatmentAssignments = new ArrayList<TreatmentAssignment>(); TreatmentAssignment treatmentAssignment; for (int tacRow = 1; tacRow <= tacRows; tacRow++) { if (primaryIdentifierString.equalsIgnoreCase(getCellData( TAC_SHEET_NAME, tacRow, tacInfoSheet.getRow(tacRow) .getCell((short) 0)))) { treatmentAssignment = new TreatmentAssignment(); treatmentAssignment.setCode(getCellData(TAC_SHEET_NAME, tacRow, tacInfoSheet.getRow(tacRow).getCell((short) 1))); treatmentAssignment .setDescription(getCellData(TAC_SHEET_NAME, tacRow, tacInfoSheet.getRow(tacRow).getCell((short) 2))); treatmentAssignment.setStudy(study); treatmentAssignments.add(treatmentAssignment); } } study.setTreatmentAssignments(treatmentAssignments); } private void setStudyOrganizations(Study study) { int orgRows = orgInfoSheet.getLastRowNum(); boolean leadOrg; StudyOrganization studyOrganization; Organization organization; for (int orgRow = 1; orgRow <= orgRows; orgRow++) { if (primaryIdentifierString.equalsIgnoreCase(getCellData( ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow) .getCell((short) 0)))) { leadOrg = getCellData(ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow).getCell((short) 1)) .equalsIgnoreCase("Lead") ? true : false; organization = new LocalOrganization(); organization.setName(getCellData(ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow).getCell((short) 2))); organization.setNciInstituteCode(formatNCIcode(getCellData( ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow) .getCell((short) 3)))); if (leadOrg) { CoordinatingCenter cc = new CoordinatingCenter(); StudyCoordinatingCenter scc = new StudyCoordinatingCenter(); Organization cco = new LocalOrganization(); cco.setName(getCellData(ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow).getCell((short) 2))); cco.setNciInstituteCode(formatNCIcode(getCellData( ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow) .getCell((short) 3)))); scc.setOrganization(cco); cc.setStudyCoordinatingCenter(scc); OrganizationAssignedIdentifier cci = new OrganizationAssignedIdentifier(); cci.setValue(localDocumentNumber); cci.setPrimaryIndicator(false); cc.setOrganizationAssignedIdentifier(cci); study.setCoordinatingCenter(cc); } else { StudySite ss = new StudySite(); ss.setOrganization(organization); study.addStudyOrganization(ss); } } } } private void setStudyTherapies(Study study) { int therapyRows = therapyInfoSheet.getLastRowNum(); for (int therapyRow = 1; therapyRow <= therapyRows; therapyRow++) { if (primaryIdentifierString.equalsIgnoreCase(getCellData( THERAPY_SHEET_NAME, therapyRow, therapyInfoSheet.getRow( therapyRow).getCell((short) 0)))) { String therapyString = getCellData(THERAPY_SHEET_NAME, therapyRow, therapyInfoSheet.getRow(therapyRow) .getCell((short) 1)); StudyTherapyType therapyType = getStudyTherapyType(therapyString); study.addStudyTherapy(therapyType); } } } private void setStudyInvestigators(Study study) { StudyCoordinatingCenter scc = study.getCoordinatingCenter().getStudyCoordinatingCenter(); setInvestigatorsInOrg(scc); for (StudySite ss : study.getStudySites()) { setInvestigatorsInOrg(ss); } } private void validateStudy(Study study) { studyImportOutcome = studyImportService.importStudy(study); List<String> errors = domainObjectValidator.validate(studyImportOutcome.getImportedDomainObject()); if (studyImportOutcome.isSavable() && errors.size() == 0) { saveStudy(studyImportOutcome.getImportedDomainObject()); } else { for(String errMsg : errors){ studyImportOutcome.addErrorMessage(errMsg, Severity.ERROR); } List<DomainObjectImportOutcome.Message> messages = studyImportOutcome .getMessages(); System.out.println("Error: Unable to save study: " + study.getShortTitle() + " -- " + study.getLongTitle()); for (Message message : messages) { System.out.println("Reason: " + message.toString()); } } } private void saveStudy(Study study) { if(fetchStudy(study) == null){ System.out.println("Study with Short Title " + study.getShortTitle() + " Created in caAERS "); studydao.save(study); }else{ System.out.println("Study with Short Title " + study.getShortTitle() + " Exists in caAERS "); } } public void setOrgdao(OrganizationDao orgdao) { this.orgdao = orgdao; } public CtcDao getCtcdao() { return ctcdao; } public void setCtcdao(CtcDao ctcdao) { this.ctcdao = ctcdao; } // utility method to get contents of cell irrespective of cell type. private String getCellData(String sheetname, int rowNum, HSSFCell cell) { if (cell == null) throw new CaaersSystemException( "Invalid data or Blank cell at following location: \n Sheet: " + sheetname + "\n Row: " + (rowNum + 1)); int cellType = cell.getCellType(); if (cellType == 0) { if (cell.getNumericCellValue() == 0) throw new CaaersSystemException( "Invalid data or Blank cell at following location: \n Sheet: " + sheetname + "\n Row: " + (rowNum + 1) + "\n Cell: " + ((cell.getCellNum()) + 1)); return (Integer.toString((int) cell.getNumericCellValue())).trim(); } else if (cellType == 1) { if (cell.getStringCellValue().equals("")) throw new CaaersSystemException( "Invalid data or Blank cell at following location: \n Sheet: " + sheetname + "\n Row: " + (rowNum + 1) + "\n Cell: " + ((cell.getCellNum()) + 1)); return cell.getStringCellValue().trim(); } else { throw new CaaersSystemException( "Invalid data or Blank cell at following location: \n Sheet: " + sheetname + "\n Row: " + (rowNum + 1) + "\n Cell: " + ((cell.getCellNum()) + 1)); } } // Converts 4 digit nci codes to 5 digits to correctly map to DB. Does not // apply to alphanumeric // strings. private String formatNCIcode(String nciCode) { if (nciCode.length() < 5) { try { int i = Integer.parseInt(nciCode); if (i / 10000 == 0) nciCode = '0' + nciCode; } catch (NumberFormatException nfe) { } } return nciCode; } // utility method to map therapy type values from excel sheet to // StudyTherapyType enum private StudyTherapyType getStudyTherapyType(String studyTherapyString) { StudyTherapyType type = null; if (studyTherapyString.equalsIgnoreCase("Drug and/or Immunotherapy")) type = StudyTherapyType.DRUG_ADMINISTRATION; if (studyTherapyString.equalsIgnoreCase("Radiation Therapy")) type = StudyTherapyType.RADIATION; return type; } // create investigators if not already present in DB private void syncInvestigators() { int invRows = investigatorInfoSheet.getLastRowNum(); List<Investigator> invList; Investigator inv; InvestigatorQuery iq; String invEmail; String invFax; String invPhone; SiteInvestigator siteInv; Organization org; String invNciId; String orgNciId; String statusMessage; for (int invRow = 1; invRow <= invRows; invRow++) { iq = new InvestigatorQuery(); invNciId = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 3)); iq.filterByNciIdentifierExactMatch(invNciId); // System.out.print(getCellData(INVESTIGATOR_SHEET_NAME, invRow, // investigatorInfoSheet.getRow(invRow).getCell((short) 3))); invList = investigatorRepository.searchInvestigator(iq); if (invList.size() == 0) { statusMessage=" Created in caAERS."; inv = new LocalInvestigator(); inv.setNciIdentifier(invNciId); inv .setLastName(getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow) .getCell((short) 4))); inv .setFirstName(getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow) .getCell((short) 5))); invEmail = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 6)); if (invEmail.equalsIgnoreCase("null")) { invEmail = "default@abc.com"; } inv.setEmailAddress(invEmail); invPhone = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 7)); if (invPhone.equalsIgnoreCase("null")) { invPhone = "(000)000-0000"; } inv.setPhoneNumber(invPhone); invFax = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 8)); if (invFax.equalsIgnoreCase("null")) { invFax = "(000)000-0000"; } inv.setFaxNumber(invFax); } else { statusMessage=" exists in caAERS. Only associated site investigators will be updated."; inv = invList.get(0); } orgNciId = formatNCIcode(getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell( (short) 1))); org = orgdao.getByNCIcode(orgNciId.trim()); boolean addSiteInv = true; List<SiteInvestigator> siteInvList = inv.getSiteInvestigators(); for (SiteInvestigator existingSiteInv : siteInvList) { if (orgNciId.equals(existingSiteInv.getOrganization().getNciInstituteCode())) { addSiteInv = false; break; } } if (addSiteInv) { siteInv = new SiteInvestigator(); siteInv.setOrganization(org); inv.addSiteInvestigator(siteInv); } investigatordao.save(inv); System.out.println("Investigator " + inv.getLastFirst() + statusMessage); } } private void setInvestigatorsInOrg(StudyOrganization so) { if (so == null) { return; } int invRows = investigatorInfoSheet.getLastRowNum(); StudyInvestigator studyInvestigator; SiteInvestigator siteInvestigator; Investigator investigator; String invStudyId; String invOrgId; for (int invRow = 1; invRow <= invRows; invRow++) { invStudyId = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 0)); invOrgId = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 1)); if (invStudyId.equalsIgnoreCase(primaryIdentifierString) && invOrgId.equalsIgnoreCase(so.getOrganization() .getNciInstituteCode())) { investigator = new LocalInvestigator(); investigator.setFirstName(getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell( (short) 5))); investigator.setLastName(getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell( (short) 4))); investigator.setNciIdentifier(getCellData( INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet .getRow(invRow).getCell((short) 3))); siteInvestigator = new SiteInvestigator(); siteInvestigator.setInvestigator(investigator); studyInvestigator = new StudyInvestigator(); studyInvestigator.setSiteInvestigator(siteInvestigator); studyInvestigator.setRoleCode(getCellData( INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet .getRow(invRow).getCell((short) 2))); studyInvestigator.setStartDate(DateUtils.yesterday()); so.addStudyInvestigators(studyInvestigator); } } } private HSSFSheet getSheet(String sheetName) { HSSFSheet sheet = wb.getSheet(sheetName); if (sheet == null) throw new CaaersSystemException("\n Unable to find sheet named: " + sheetName + "\n Please fix the error and try again."); else return sheet; } /** * This method fetches a Study from the DB based identifiers. * @param importedStudy * @return */ private Study fetchStudy(Study importedStudy){ Study dbStudy = null; for (Identifier identifier : importedStudy.getIdentifiers()) { dbStudy = studydao.getStudyDesignByIdentifier(identifier); if(dbStudy != null){ break; } studydao.evict(dbStudy); } return dbStudy; } /* * // bringing back DB to original state to facilitate testing private void * cleanStudies() { for (int i = 1; i < studyInfoSheet.getLastRowNum(); i++) { * Study s = studydao.getByShortTitle(getCellData(STUDY_SHEET_NAME, * i,(studyInfoSheet.getRow(i) .getCell((short) 1)))); if (s != null) * studydao.delete(s); } } */ public void setStudydao(StudyDao studydao) { this.studydao = studydao; } public void setAgentdao(AgentDao agentdao) { this.agentdao = agentdao; } public void setInvestigationalnewdrugdao( InvestigationalNewDrugDao investigationalnewdrugdao) { this.investigationalnewdrugdao = investigationalnewdrugdao; } public void setDiseasetermdao(DiseaseTermDao diseasetermdao) { this.diseasetermdao = diseasetermdao; } public void setInvestigatordao(InvestigatorDao investigatordao) { this.investigatordao = investigatordao; } public void setStudyImportService(StudyImportServiceImpl studyImportService) { this.studyImportService = studyImportService; } public void setDomainObjectValidator(DomainObjectValidator domainObjectValidator) { this.domainObjectValidator = domainObjectValidator; } public InvestigatorRepository getInvestigatorRepository() { return investigatorRepository; } public void setInvestigatorRepository( InvestigatorRepository investigatorRepository) { this.investigatorRepository = investigatorRepository; } }
caAERS/software/excelstudyloader/src/main/java/gov/nih/nci/cabig/caaers/tools/ExcelProcessor.java
package gov.nih.nci.cabig.caaers.tools; import gov.nih.nci.cabig.caaers.CaaersSystemException; import gov.nih.nci.cabig.caaers.dao.AgentDao; import gov.nih.nci.cabig.caaers.dao.CtcDao; import gov.nih.nci.cabig.caaers.dao.DiseaseTermDao; import gov.nih.nci.cabig.caaers.dao.InvestigationalNewDrugDao; import gov.nih.nci.cabig.caaers.dao.InvestigatorDao; import gov.nih.nci.cabig.caaers.dao.OrganizationDao; import gov.nih.nci.cabig.caaers.dao.StudyDao; import gov.nih.nci.cabig.caaers.dao.query.InvestigatorQuery; import gov.nih.nci.cabig.caaers.domain.AeTerminology; import gov.nih.nci.cabig.caaers.domain.CoordinatingCenter; import gov.nih.nci.cabig.caaers.domain.Ctc; import gov.nih.nci.cabig.caaers.domain.CtepStudyDisease; import gov.nih.nci.cabig.caaers.domain.DiseaseCodeTerm; import gov.nih.nci.cabig.caaers.domain.DiseaseTerminology; import gov.nih.nci.cabig.caaers.domain.FundingSponsor; import gov.nih.nci.cabig.caaers.domain.INDType; import gov.nih.nci.cabig.caaers.domain.Identifier; import gov.nih.nci.cabig.caaers.domain.Investigator; import gov.nih.nci.cabig.caaers.domain.LocalInvestigator; import gov.nih.nci.cabig.caaers.domain.LocalOrganization; import gov.nih.nci.cabig.caaers.domain.LocalStudy; import gov.nih.nci.cabig.caaers.domain.Organization; import gov.nih.nci.cabig.caaers.domain.OrganizationAssignedIdentifier; import gov.nih.nci.cabig.caaers.domain.SiteInvestigator; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyAgent; import gov.nih.nci.cabig.caaers.domain.StudyAgentINDAssociation; import gov.nih.nci.cabig.caaers.domain.StudyCoordinatingCenter; import gov.nih.nci.cabig.caaers.domain.StudyFundingSponsor; import gov.nih.nci.cabig.caaers.domain.StudyInvestigator; import gov.nih.nci.cabig.caaers.domain.StudyOrganization; import gov.nih.nci.cabig.caaers.domain.StudySite; import gov.nih.nci.cabig.caaers.domain.StudyTherapyType; import gov.nih.nci.cabig.caaers.domain.TreatmentAssignment; import gov.nih.nci.cabig.caaers.domain.repository.InvestigatorRepository; import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome; import gov.nih.nci.cabig.caaers.service.StudyImportServiceImpl; import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome.Message; import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome.Severity; import gov.nih.nci.cabig.caaers.utils.DateUtils; import gov.nih.nci.cabig.caaers.validation.validator.DomainObjectValidator; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; public class ExcelProcessor { private POIFSFileSystem poifs; private HSSFWorkbook wb; private HSSFSheet studyInfoSheet; private HSSFSheet agentInfoSheet; private HSSFSheet diseaseInfoSheet; private HSSFSheet tacInfoSheet; private HSSFSheet orgInfoSheet; private HSSFSheet investigatorInfoSheet; private HSSFSheet therapyInfoSheet; // Study related objects private Study study; private OrganizationDao orgdao; private CtcDao ctcdao; private StudyDao studydao; private AgentDao agentdao; private InvestigationalNewDrugDao investigationalnewdrugdao; private DiseaseTermDao diseasetermdao; private InvestigatorDao investigatordao; private InvestigatorRepository investigatorRepository; private StudyImportServiceImpl studyImportService; private String primaryIdentifierString; private String localDocumentNumber; private String studyTitle; private String phaseCode; private DiseaseTerminology diseaseTerminology; private AeTerminology aeTerminology; private DomainObjectImportOutcome<Study> studyImportOutcome; private DomainObjectValidator domainObjectValidator; private int rowCount = 0; private final String STUDY_SHEET_NAME = "admin info"; private final String AGENT_SHEET_NAME = "agent info"; private final String DISEASE_SHEET_NAME = "disease info"; private final String TAC_SHEET_NAME = "TAC info"; private final String ORG_SHEET_NAME = "organizations"; private final String INVESTIGATOR_SHEET_NAME = "investigators"; private final String THERAPY_SHEET_NAME = "therapies"; public ExcelProcessor() { } public void processExcel(File inputFile) throws Exception { bootstrap(inputFile); syncInvestigators(); while (rowCount > 0) { study = new LocalStudy(); initializeStudy(study); setStudyAgents(study); setStudyDiseases(study); setStudyTreatmentAssignments(study); setStudyOrganizations(study); setStudyInvestigators(study); setStudyTherapies(study); validateStudy(study); rowCount--; } System.out.println("Excel Import Complete"); System.out.println(""); System.out.println("Excel Import Summary"); System.out.println("-----------------------------------------------------------"); System.out.println("Total Number of Investigators Processed ---> "+investigatorInfoSheet.getLastRowNum()); System.out.println("Total Number of Studies Processed ---> "+studyInfoSheet.getLastRowNum()); System.out.println("-----------------------------------------------------------"); } private void bootstrap(File inputFile) throws Exception { poifs = new POIFSFileSystem(new FileInputStream(inputFile)); // create a workbook out of the input stream wb = new HSSFWorkbook(poifs); studyInfoSheet = getSheet(STUDY_SHEET_NAME); agentInfoSheet = getSheet(AGENT_SHEET_NAME); diseaseInfoSheet = getSheet(DISEASE_SHEET_NAME); tacInfoSheet = getSheet(TAC_SHEET_NAME); orgInfoSheet = getSheet(ORG_SHEET_NAME); investigatorInfoSheet = getSheet(INVESTIGATOR_SHEET_NAME); therapyInfoSheet = getSheet(THERAPY_SHEET_NAME); rowCount = studyInfoSheet.getLastRowNum(); } private void initializeStudy(Study study) { primaryIdentifierString = getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet.getRow(rowCount).getCell((short) 0)); localDocumentNumber = getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet.getRow(rowCount).getCell((short) 1)); studyTitle = getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet .getRow(rowCount).getCell((short) 2)); phaseCode = getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet .getRow(rowCount).getCell((short) 3)); FundingSponsor fs = new FundingSponsor(); StudyFundingSponsor sfs = new StudyFundingSponsor(); Organization fo = new LocalOrganization(); fo.setName("Cancer Therapy Evaluation Program"); sfs.setOrganization(fo); fs.setStudyFundingSponsor(sfs); OrganizationAssignedIdentifier sfi = new OrganizationAssignedIdentifier(); sfi.setValue(getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet .getRow(rowCount).getCell((short) 0))); sfi.setPrimaryIndicator(true); fs.setOrganizationAssignedIdentifier(sfi); study.setFundingSponsor(fs); //study.setShortTitle(localDocumentNumber); study.setShortTitle(studyTitle); study.setLongTitle(studyTitle); aeTerminology = study.getAeTerminology(); Ctc ctc = new Ctc(); ctc.setName(getCellData(STUDY_SHEET_NAME, rowCount, studyInfoSheet .getRow(rowCount).getCell((short) 4))); aeTerminology.setCtcVersion(ctc); study.setAeTerminology(aeTerminology); study.setDescription(studyTitle); diseaseTerminology = study.getDiseaseTerminology(); diseaseTerminology.setDiseaseCodeTerm(DiseaseCodeTerm.getByCode(1)); study.setDiseaseTerminology(diseaseTerminology); study.setMultiInstitutionIndicator(true); study.setStatus(gov.nih.nci.cabig.caaers.domain.Study.STATUS_ACTIVE); study.setAdeersReporting(Boolean.TRUE); if("I".equals(phaseCode)){ study.setPhaseCode("Phase I Trial"); } if("II".equals(phaseCode)){ study.setPhaseCode("Phase II Trial"); } if("I/II".equals(phaseCode)){ study.setPhaseCode("Phase I/II Trial"); } if("III".equals(phaseCode)){ study.setPhaseCode("Phase III Trial"); } if("II/III".equals(phaseCode)){ study.setPhaseCode("Phase II/III Trial"); } if("IV".equals(phaseCode)){ study.setPhaseCode("Phase IV Trial"); } if("0".equals(phaseCode)){ study.setPhaseCode("Phase 0 Trial"); } if("Pilot".equals(phaseCode)){ study.setPhaseCode("Pilot"); } } private void setStudyAgents(Study study) { int agentRows = agentInfoSheet.getLastRowNum(); List<StudyAgent> studyAgents = new ArrayList<StudyAgent>(); StudyAgent studyAgent = null; INDType indType; String indNumber; List<StudyAgentINDAssociation> studyAgentINDAssociations; StudyAgentINDAssociation studyAgentINDAssociation; for (int agentRow = 1; agentRow <= agentRows; agentRow++) { if (primaryIdentifierString.equalsIgnoreCase(getCellData( AGENT_SHEET_NAME, agentRow, agentInfoSheet.getRow(agentRow) .getCell((short) 0)))) { studyAgent = new StudyAgent(agentdao .getByNscNumber(getCellData(AGENT_SHEET_NAME, agentRow, agentInfoSheet.getRow(agentRow).getCell( (short) 2)))); studyAgent.setStudy(study); indType = getCellData(AGENT_SHEET_NAME, agentRow, agentInfoSheet.getRow(agentRow).getCell((short) 4)) .equalsIgnoreCase("Investigational") ? INDType.CTEP_IND : INDType.NA_COMMERCIAL; studyAgent.setIndType(indType); studyAgent.setPartOfLeadIND(getCellData(AGENT_SHEET_NAME, agentRow, (agentInfoSheet.getRow(agentRow).getCell((short) 3))) .equalsIgnoreCase("Yes") ? true : false); indNumber = getCellData(AGENT_SHEET_NAME, agentRow, agentInfoSheet.getRow(agentRow).getCell((short) 6)); if (!(indNumber.equalsIgnoreCase("null"))) { studyAgentINDAssociation = new StudyAgentINDAssociation(); studyAgentINDAssociation.setStudyAgent(studyAgent); studyAgentINDAssociation .setInvestigationalNewDrug(investigationalnewdrugdao .fetchCtepInd()); studyAgentINDAssociations = new ArrayList<StudyAgentINDAssociation>(); studyAgentINDAssociations.add(studyAgentINDAssociation); studyAgent .setStudyAgentINDAssociations(studyAgentINDAssociations); } studyAgents.add(studyAgent); } } study.setStudyAgents(studyAgents); } private void setStudyDiseases(Study study) { int diseaseRows = diseaseInfoSheet.getLastRowNum(); List<CtepStudyDisease> ctepStudyDiseases = new ArrayList<CtepStudyDisease>(); CtepStudyDisease ctepStudyDisease = null; String diseaseTermString = null; boolean leadDisease; for (int diseaseRow = 1; diseaseRow <= diseaseRows; diseaseRow++) { if (primaryIdentifierString.equalsIgnoreCase(getCellData( DISEASE_SHEET_NAME, diseaseRow, diseaseInfoSheet.getRow( diseaseRow).getCell((short) 0)))) { diseaseTermString = getCellData(DISEASE_SHEET_NAME, diseaseRow, diseaseInfoSheet.getRow(diseaseRow).getCell((short) 1)); ctepStudyDisease = new CtepStudyDisease(); ctepStudyDisease.setDiseaseTerm(diseasetermdao .getByCTEPTermName(diseaseTermString)); leadDisease = getCellData(DISEASE_SHEET_NAME, diseaseRow, diseaseInfoSheet.getRow(diseaseRow).getCell((short) 2)) .equalsIgnoreCase("Yes") ? true : false; ctepStudyDisease.setLeadDisease(leadDisease); ctepStudyDiseases.add(ctepStudyDisease); } } study.setCtepStudyDiseases(ctepStudyDiseases); } private void setStudyTreatmentAssignments(Study study) { int tacRows = tacInfoSheet.getLastRowNum(); List<TreatmentAssignment> treatmentAssignments = new ArrayList<TreatmentAssignment>(); TreatmentAssignment treatmentAssignment; for (int tacRow = 1; tacRow <= tacRows; tacRow++) { if (primaryIdentifierString.equalsIgnoreCase(getCellData( TAC_SHEET_NAME, tacRow, tacInfoSheet.getRow(tacRow) .getCell((short) 0)))) { treatmentAssignment = new TreatmentAssignment(); treatmentAssignment.setCode(getCellData(TAC_SHEET_NAME, tacRow, tacInfoSheet.getRow(tacRow).getCell((short) 1))); treatmentAssignment .setDescription(getCellData(TAC_SHEET_NAME, tacRow, tacInfoSheet.getRow(tacRow).getCell((short) 2))); treatmentAssignment.setStudy(study); treatmentAssignments.add(treatmentAssignment); } } study.setTreatmentAssignments(treatmentAssignments); } private void setStudyOrganizations(Study study) { int orgRows = orgInfoSheet.getLastRowNum(); boolean leadOrg; StudyOrganization studyOrganization; Organization organization; for (int orgRow = 1; orgRow <= orgRows; orgRow++) { if (primaryIdentifierString.equalsIgnoreCase(getCellData( ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow) .getCell((short) 0)))) { leadOrg = getCellData(ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow).getCell((short) 1)) .equalsIgnoreCase("Lead") ? true : false; organization = new LocalOrganization(); organization.setName(getCellData(ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow).getCell((short) 2))); organization.setNciInstituteCode(formatNCIcode(getCellData( ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow) .getCell((short) 3)))); if (leadOrg) { CoordinatingCenter cc = new CoordinatingCenter(); StudyCoordinatingCenter scc = new StudyCoordinatingCenter(); Organization cco = new LocalOrganization(); cco.setName(getCellData(ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow).getCell((short) 2))); cco.setNciInstituteCode(formatNCIcode(getCellData( ORG_SHEET_NAME, orgRow, orgInfoSheet.getRow(orgRow) .getCell((short) 3)))); scc.setOrganization(cco); cc.setStudyCoordinatingCenter(scc); OrganizationAssignedIdentifier cci = new OrganizationAssignedIdentifier(); cci.setValue(localDocumentNumber); cci.setPrimaryIndicator(false); cc.setOrganizationAssignedIdentifier(cci); study.setCoordinatingCenter(cc); } else { StudySite ss = new StudySite(); ss.setOrganization(organization); study.addStudyOrganization(ss); } } } } private void setStudyTherapies(Study study) { int therapyRows = therapyInfoSheet.getLastRowNum(); for (int therapyRow = 1; therapyRow <= therapyRows; therapyRow++) { if (primaryIdentifierString.equalsIgnoreCase(getCellData( THERAPY_SHEET_NAME, therapyRow, therapyInfoSheet.getRow( therapyRow).getCell((short) 0)))) { String therapyString = getCellData(THERAPY_SHEET_NAME, therapyRow, therapyInfoSheet.getRow(therapyRow) .getCell((short) 1)); if (getStudyTherapyType(therapyString).equals( StudyTherapyType.DRUG_ADMINISTRATION)) { study.setDrugAdministrationTherapyType(Boolean.TRUE); } if (getStudyTherapyType(therapyString).equals( StudyTherapyType.RADIATION)) { study.setRadiationTherapyType(Boolean.TRUE); } } } } private void setStudyInvestigators(Study study) { StudyCoordinatingCenter scc = study.getCoordinatingCenter().getStudyCoordinatingCenter(); setInvestigatorsInOrg(scc); for (StudySite ss : study.getStudySites()) { setInvestigatorsInOrg(ss); } } private void validateStudy(Study study) { studyImportOutcome = studyImportService.importStudy(study); List<String> errors = domainObjectValidator.validate(studyImportOutcome.getImportedDomainObject()); if (studyImportOutcome.isSavable() && errors.size() == 0) { saveStudy(studyImportOutcome.getImportedDomainObject()); } else { for(String errMsg : errors){ studyImportOutcome.addErrorMessage(errMsg, Severity.ERROR); } List<DomainObjectImportOutcome.Message> messages = studyImportOutcome .getMessages(); System.out.println("Error: Unable to save study: " + study.getShortTitle() + " -- " + study.getLongTitle()); for (Message message : messages) { System.out.println("Reason: " + message.toString()); } } } private void saveStudy(Study study) { if(fetchStudy(study) == null){ System.out.println("Study with Short Title " + study.getShortTitle() + " Created in caAERS "); studydao.save(study); }else{ System.out.println("Study with Short Title " + study.getShortTitle() + " Exists in caAERS "); } } public void setOrgdao(OrganizationDao orgdao) { this.orgdao = orgdao; } public CtcDao getCtcdao() { return ctcdao; } public void setCtcdao(CtcDao ctcdao) { this.ctcdao = ctcdao; } // utility method to get contents of cell irrespective of cell type. private String getCellData(String sheetname, int rowNum, HSSFCell cell) { if (cell == null) throw new CaaersSystemException( "Invalid data or Blank cell at following location: \n Sheet: " + sheetname + "\n Row: " + (rowNum + 1)); int cellType = cell.getCellType(); if (cellType == 0) { if (cell.getNumericCellValue() == 0) throw new CaaersSystemException( "Invalid data or Blank cell at following location: \n Sheet: " + sheetname + "\n Row: " + (rowNum + 1) + "\n Cell: " + ((cell.getCellNum()) + 1)); return (Integer.toString((int) cell.getNumericCellValue())).trim(); } else if (cellType == 1) { if (cell.getStringCellValue().equals("")) throw new CaaersSystemException( "Invalid data or Blank cell at following location: \n Sheet: " + sheetname + "\n Row: " + (rowNum + 1) + "\n Cell: " + ((cell.getCellNum()) + 1)); return cell.getStringCellValue().trim(); } else { throw new CaaersSystemException( "Invalid data or Blank cell at following location: \n Sheet: " + sheetname + "\n Row: " + (rowNum + 1) + "\n Cell: " + ((cell.getCellNum()) + 1)); } } // Converts 4 digit nci codes to 5 digits to correctly map to DB. Does not // apply to alphanumeric // strings. private String formatNCIcode(String nciCode) { if (nciCode.length() < 5) { try { int i = Integer.parseInt(nciCode); if (i / 10000 == 0) nciCode = '0' + nciCode; } catch (NumberFormatException nfe) { } } return nciCode; } // utility method to map therapy type values from excel sheet to // StudyTherapyType enum private StudyTherapyType getStudyTherapyType(String studyTherapyString) { StudyTherapyType type = null; if (studyTherapyString.equalsIgnoreCase("Drug and/or Immunotherapy")) type = StudyTherapyType.DRUG_ADMINISTRATION; if (studyTherapyString.equalsIgnoreCase("Radiation Therapy")) type = StudyTherapyType.RADIATION; return type; } // create investigators if not already present in DB private void syncInvestigators() { int invRows = investigatorInfoSheet.getLastRowNum(); List<Investigator> invList; Investigator inv; InvestigatorQuery iq; String invEmail; String invFax; String invPhone; SiteInvestigator siteInv; Organization org; String invNciId; String orgNciId; String statusMessage; for (int invRow = 1; invRow <= invRows; invRow++) { iq = new InvestigatorQuery(); invNciId = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 3)); iq.filterByNciIdentifierExactMatch(invNciId); // System.out.print(getCellData(INVESTIGATOR_SHEET_NAME, invRow, // investigatorInfoSheet.getRow(invRow).getCell((short) 3))); invList = investigatorRepository.searchInvestigator(iq); if (invList.size() == 0) { statusMessage=" Created in caAERS."; inv = new LocalInvestigator(); inv.setNciIdentifier(invNciId); inv .setLastName(getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow) .getCell((short) 4))); inv .setFirstName(getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow) .getCell((short) 5))); invEmail = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 6)); if (invEmail.equalsIgnoreCase("null")) { invEmail = "default@abc.com"; } inv.setEmailAddress(invEmail); invPhone = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 7)); if (invPhone.equalsIgnoreCase("null")) { invPhone = "(000)000-0000"; } inv.setPhoneNumber(invPhone); invFax = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 8)); if (invFax.equalsIgnoreCase("null")) { invFax = "(000)000-0000"; } inv.setFaxNumber(invFax); } else { statusMessage=" exists in caAERS. Only associated site investigators will be updated."; inv = invList.get(0); } orgNciId = formatNCIcode(getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell( (short) 1))); org = orgdao.getByNCIcode(orgNciId.trim()); boolean addSiteInv = true; List<SiteInvestigator> siteInvList = inv.getSiteInvestigators(); for (SiteInvestigator existingSiteInv : siteInvList) { if (orgNciId.equals(existingSiteInv.getOrganization().getNciInstituteCode())) { addSiteInv = false; break; } } if (addSiteInv) { siteInv = new SiteInvestigator(); siteInv.setOrganization(org); inv.addSiteInvestigator(siteInv); } investigatordao.save(inv); System.out.println("Investigator " + inv.getLastFirst() + statusMessage); } } private void setInvestigatorsInOrg(StudyOrganization so) { if (so == null) { return; } int invRows = investigatorInfoSheet.getLastRowNum(); StudyInvestigator studyInvestigator; SiteInvestigator siteInvestigator; Investigator investigator; String invStudyId; String invOrgId; for (int invRow = 1; invRow <= invRows; invRow++) { invStudyId = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 0)); invOrgId = getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell((short) 1)); if (invStudyId.equalsIgnoreCase(primaryIdentifierString) && invOrgId.equalsIgnoreCase(so.getOrganization() .getNciInstituteCode())) { investigator = new LocalInvestigator(); investigator.setFirstName(getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell( (short) 5))); investigator.setLastName(getCellData(INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet.getRow(invRow).getCell( (short) 4))); investigator.setNciIdentifier(getCellData( INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet .getRow(invRow).getCell((short) 3))); siteInvestigator = new SiteInvestigator(); siteInvestigator.setInvestigator(investigator); studyInvestigator = new StudyInvestigator(); studyInvestigator.setSiteInvestigator(siteInvestigator); studyInvestigator.setRoleCode(getCellData( INVESTIGATOR_SHEET_NAME, invRow, investigatorInfoSheet .getRow(invRow).getCell((short) 2))); studyInvestigator.setStartDate(DateUtils.yesterday()); so.addStudyInvestigators(studyInvestigator); } } } private HSSFSheet getSheet(String sheetName) { HSSFSheet sheet = wb.getSheet(sheetName); if (sheet == null) throw new CaaersSystemException("\n Unable to find sheet named: " + sheetName + "\n Please fix the error and try again."); else return sheet; } /** * This method fetches a Study from the DB based identifiers. * @param importedStudy * @return */ private Study fetchStudy(Study importedStudy){ Study dbStudy = null; for (Identifier identifier : importedStudy.getIdentifiers()) { dbStudy = studydao.getStudyDesignByIdentifier(identifier); if(dbStudy != null){ break; } studydao.evict(dbStudy); } return dbStudy; } /* * // bringing back DB to original state to facilitate testing private void * cleanStudies() { for (int i = 1; i < studyInfoSheet.getLastRowNum(); i++) { * Study s = studydao.getByShortTitle(getCellData(STUDY_SHEET_NAME, * i,(studyInfoSheet.getRow(i) .getCell((short) 1)))); if (s != null) * studydao.delete(s); } } */ public void setStudydao(StudyDao studydao) { this.studydao = studydao; } public void setAgentdao(AgentDao agentdao) { this.agentdao = agentdao; } public void setInvestigationalnewdrugdao( InvestigationalNewDrugDao investigationalnewdrugdao) { this.investigationalnewdrugdao = investigationalnewdrugdao; } public void setDiseasetermdao(DiseaseTermDao diseasetermdao) { this.diseasetermdao = diseasetermdao; } public void setInvestigatordao(InvestigatorDao investigatordao) { this.investigatordao = investigatordao; } public void setStudyImportService(StudyImportServiceImpl studyImportService) { this.studyImportService = studyImportService; } public void setDomainObjectValidator(DomainObjectValidator domainObjectValidator) { this.domainObjectValidator = domainObjectValidator; } public InvestigatorRepository getInvestigatorRepository() { return investigatorRepository; } public void setInvestigatorRepository( InvestigatorRepository investigatorRepository) { this.investigatorRepository = investigatorRepository; } }
CAAERS-3121 - Provided ability to migrate PlannedActivity (Interventions). SVN-Revision: 10942
caAERS/software/excelstudyloader/src/main/java/gov/nih/nci/cabig/caaers/tools/ExcelProcessor.java
CAAERS-3121 - Provided ability to migrate PlannedActivity (Interventions).
Java
bsd-3-clause
b992c46ca9cf7efd1c368bb4e03eb1bb8f635dd8
0
uonafya/jphes-core,uonafya/jphes-core,uonafya/jphes-core,uonafya/jphes-core,uonafya/jphes-core
package org.hisp.dhis.dxf2.events.event; /* * Copyright (c) 2004-2016, University of Oslo * 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 HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.SessionFactory; import org.hisp.dhis.common.CodeGenerator; import org.hisp.dhis.common.IdScheme; import org.hisp.dhis.common.IdSchemes; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.common.IllegalQueryException; import org.hisp.dhis.common.OrganisationUnitSelectionMode; import org.hisp.dhis.common.Pager; import org.hisp.dhis.commons.collection.CachingMap; import org.hisp.dhis.commons.util.DebugUtils; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo; import org.hisp.dhis.dataelement.DataElementCategoryService; import org.hisp.dhis.dataelement.DataElementService; import org.hisp.dhis.dbms.DbmsManager; import org.hisp.dhis.dxf2.common.ImportOptions; import org.hisp.dhis.dxf2.events.enrollment.EnrollmentStatus; import org.hisp.dhis.dxf2.events.report.EventRow; import org.hisp.dhis.dxf2.events.report.EventRows; import org.hisp.dhis.dxf2.importsummary.ImportConflict; import org.hisp.dhis.dxf2.importsummary.ImportStatus; import org.hisp.dhis.dxf2.importsummary.ImportSummaries; import org.hisp.dhis.dxf2.importsummary.ImportSummary; import org.hisp.dhis.dxf2.utils.InputUtils; import org.hisp.dhis.event.EventStatus; import org.hisp.dhis.fileresource.FileResourceService; import org.hisp.dhis.i18n.I18nManager; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.organisationunit.OrganisationUnitService; import org.hisp.dhis.period.Period; import org.hisp.dhis.period.PeriodType; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramInstance; import org.hisp.dhis.program.ProgramInstanceService; import org.hisp.dhis.program.ProgramService; import org.hisp.dhis.program.ProgramStage; import org.hisp.dhis.program.ProgramStageInstance; import org.hisp.dhis.program.ProgramStageInstanceService; import org.hisp.dhis.program.ProgramStageService; import org.hisp.dhis.program.ProgramStatus; import org.hisp.dhis.program.ProgramType; import org.hisp.dhis.query.Order; import org.hisp.dhis.scheduling.TaskId; import org.hisp.dhis.system.callable.IdentifiableObjectCallable; import org.hisp.dhis.system.notification.NotificationLevel; import org.hisp.dhis.system.notification.Notifier; import org.hisp.dhis.system.util.DateUtils; import org.hisp.dhis.system.util.ValidationUtils; import org.hisp.dhis.trackedentity.TrackedEntityInstance; import org.hisp.dhis.trackedentity.TrackedEntityInstanceService; import org.hisp.dhis.trackedentitycomment.TrackedEntityComment; import org.hisp.dhis.trackedentitycomment.TrackedEntityCommentService; import org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValue; import org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValueService; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.User; import org.hisp.dhis.user.UserCredentials; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static org.hisp.dhis.system.notification.NotificationLevel.ERROR; /** * @author Morten Olav Hansen <mortenoh@gmail.com> */ @Transactional public abstract class AbstractEventService implements EventService { private static final Log log = LogFactory.getLog( AbstractEventService.class ); // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- @Autowired protected ProgramService programService; @Autowired protected ProgramStageService programStageService; @Autowired protected ProgramInstanceService programInstanceService; @Autowired protected ProgramStageInstanceService programStageInstanceService; @Autowired protected OrganisationUnitService organisationUnitService; @Autowired protected DataElementService dataElementService; @Autowired protected CurrentUserService currentUserService; @Autowired protected TrackedEntityDataValueService dataValueService; @Autowired protected TrackedEntityInstanceService entityInstanceService; @Autowired protected TrackedEntityCommentService commentService; @Autowired protected EventStore eventStore; @Autowired protected I18nManager i18nManager; @Autowired protected Notifier notifier; @Autowired protected SessionFactory sessionFactory; @Autowired protected DbmsManager dbmsManager; @Autowired protected IdentifiableObjectManager manager; @Autowired protected DataElementCategoryService categoryService; @Autowired protected InputUtils inputUtils; @Autowired protected FileResourceService fileResourceService; protected static final int FLUSH_FREQUENCY = 20; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); // ------------------------------------------------------------------------- // Caches // ------------------------------------------------------------------------- private CachingMap<String, OrganisationUnit> organisationUnitCache = new CachingMap<>(); private CachingMap<String, Program> programCache = new CachingMap<>(); private CachingMap<String, ProgramStage> programStageCache = new CachingMap<>(); private CachingMap<String, DataElement> dataElementCache = new CachingMap<>(); private Set<Program> accessibleProgramsCache = new HashSet<>(); // ------------------------------------------------------------------------- // CREATE // ------------------------------------------------------------------------- @Override public ImportSummaries addEvents( List<Event> events, ImportOptions importOptions ) { ImportSummaries importSummaries = new ImportSummaries(); int counter = 0; User user = currentUserService.getCurrentUser(); for ( Event event : events ) { importSummaries.addImportSummary( addEvent( event, user, importOptions ) ); if ( counter % FLUSH_FREQUENCY == 0 ) { dbmsManager.clearSession(); } counter++; } return importSummaries; } @Override public ImportSummaries addEvents( List<Event> events, ImportOptions importOptions, TaskId taskId ) { notifier.clear( taskId ).notify( taskId, "Importing events" ); try { ImportSummaries importSummaries = addEvents( events, importOptions ); if ( taskId != null ) { notifier.notify( taskId, NotificationLevel.INFO, "Import done", true ).addTaskSummary( taskId, importSummaries ); } return importSummaries; } catch ( RuntimeException ex ) { log.error( DebugUtils.getStackTrace( ex ) ); notifier.notify( taskId, ERROR, "Process failed: " + ex.getMessage(), true ); return new ImportSummaries().addImportSummary( new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() ) ); } } @Override public ImportSummary addEvent( Event event, ImportOptions importOptions ) { return addEvent( event, currentUserService.getCurrentUser(), importOptions ); } protected ImportSummary addEvent( Event event, User user, ImportOptions importOptions ) { if ( importOptions == null ) { importOptions = new ImportOptions(); } Program program = getProgram( importOptions.getIdSchemes().getProgramIdScheme(), event.getProgram() ); ProgramStage programStage = getProgramStage( importOptions.getIdSchemes().getProgramStageIdScheme(), event.getProgramStage() ); ProgramInstance programInstance; ProgramStageInstance programStageInstance = null; if ( program == null ) { return new ImportSummary( ImportStatus.ERROR, "Event.program does not point to a valid program: " + event.getProgram() ).incrementIgnored(); } if ( programStage == null && program.isRegistration() ) { return new ImportSummary( ImportStatus.ERROR, "Event.programStage does not point to a valid programStage, and program is multi stage: " + event.getProgramStage() ).incrementIgnored(); } else if ( programStage == null ) { programStage = program.getProgramStageByStage( 1 ); } Assert.notNull( program ); Assert.notNull( programStage ); if ( !canAccess( program, user ) ) { return new ImportSummary( ImportStatus.ERROR, "Current user does not have permission to access this program" ).incrementIgnored(); } if ( program.isRegistration() ) { if ( event.getTrackedEntityInstance() == null ) { return new ImportSummary( ImportStatus.ERROR, "No Event.trackedEntityInstance was provided for registration based program" ).incrementIgnored(); } org.hisp.dhis.trackedentity.TrackedEntityInstance entityInstance = entityInstanceService .getTrackedEntityInstance( event.getTrackedEntityInstance() ); if ( entityInstance == null ) { return new ImportSummary( ImportStatus.ERROR, "Event.trackedEntityInstance does not point to a valid tracked entity instance: " + event.getTrackedEntityInstance() ).incrementIgnored(); } List<ProgramInstance> programInstances = new ArrayList<>( programInstanceService.getProgramInstances( entityInstance, program, ProgramStatus.ACTIVE ) ); if ( programInstances.isEmpty() ) { return new ImportSummary( ImportStatus.ERROR, "Tracked entity instance: " + entityInstance.getUid() + " is not enrolled in program: " + program.getUid() ).incrementIgnored(); } else if ( programInstances.size() > 1 ) { return new ImportSummary( ImportStatus.ERROR, "Tracked entity instance: " + entityInstance.getUid() + " have multiple active enrollments in program: " + program.getUid() ).incrementIgnored(); } programInstance = programInstances.get( 0 ); if ( !programStage.getRepeatable() ) { programStageInstance = programStageInstanceService.getProgramStageInstance( programInstance, programStage ); if ( programStageInstance != null ) { return new ImportSummary( ImportStatus.ERROR, "Program stage is not repeatable and an event already exists" ).incrementIgnored(); } } else { if ( event.getEvent() != null ) { programStageInstance = programStageInstanceService.getProgramStageInstance( event.getEvent() ); if ( programStageInstance == null ) { if ( !CodeGenerator.isValidCode( event.getEvent() ) ) { return new ImportSummary( ImportStatus.ERROR, "Event.event did not point to a valid event: " + event.getEvent() ).incrementIgnored(); } } } } } else { List<ProgramInstance> programInstances = new ArrayList<>( programInstanceService.getProgramInstances( program, ProgramStatus.ACTIVE ) ); if ( programInstances.isEmpty() ) { // Create PI if it doesn't exist (should only be one) ProgramInstance pi = new ProgramInstance(); pi.setEnrollmentDate( new Date() ); pi.setIncidentDate( new Date() ); pi.setProgram( program ); pi.setStatus( ProgramStatus.ACTIVE ); programInstanceService.addProgramInstance( pi ); programInstances.add( pi ); } else if ( programInstances.size() > 1 ) { return new ImportSummary( ImportStatus.ERROR, "Multiple active program instances exists for program: " + program.getUid() ).incrementIgnored(); } programInstance = programInstances.get( 0 ); if ( event.getEvent() != null ) { programStageInstance = programStageInstanceService.getProgramStageInstance( event.getEvent() ); if ( programStageInstance == null ) { if ( !CodeGenerator.isValidCode( event.getEvent() ) ) { return new ImportSummary( ImportStatus.ERROR, "Event.event did not point to a valid event: " + event.getEvent() ).incrementIgnored(); } } } } OrganisationUnit organisationUnit = getOrganisationUnit( importOptions.getIdSchemes(), event.getOrgUnit() ); if ( organisationUnit == null ) { return new ImportSummary( ImportStatus.ERROR, "Event.orgUnit does not point to a valid organisation unit: " + event.getOrgUnit() ).incrementIgnored(); } if ( !program.hasOrganisationUnit( organisationUnit ) ) { return new ImportSummary( ImportStatus.ERROR, "Program is not assigned to this organisation unit: " + event.getOrgUnit() ).incrementIgnored(); } validateExpiryDays( event, program, null ); return saveEvent( program, programInstance, programStage, programStageInstance, organisationUnit, event, user, importOptions ); } // ------------------------------------------------------------------------- // READ // ------------------------------------------------------------------------- @Override public Events getEvents( EventSearchParams params ) { validate( params ); List<OrganisationUnit> organisationUnits = new ArrayList<>(); OrganisationUnit orgUnit = params.getOrgUnit(); OrganisationUnitSelectionMode orgUnitSelectionMode = params.getOrgUnitSelectionMode(); if ( params.getOrgUnit() != null ) { if ( OrganisationUnitSelectionMode.DESCENDANTS.equals( orgUnitSelectionMode ) ) { organisationUnits.addAll( organisationUnitService.getOrganisationUnitWithChildren( orgUnit.getUid() ) ); } else if ( OrganisationUnitSelectionMode.CHILDREN.equals( orgUnitSelectionMode ) ) { organisationUnits.add( orgUnit ); organisationUnits.addAll( orgUnit.getChildren() ); } else // SELECTED { organisationUnits.add( orgUnit ); } } if ( !params.isPaging() && !params.isSkipPaging() ) { params.setDefaultPaging(); } Events events = new Events(); if ( params.isPaging() ) { int count = 0; if ( params.isTotalPages() ) { count = eventStore.getEventCount( params, organisationUnits ); } Pager pager = new Pager( params.getPageWithDefault(), count, params.getPageSizeWithDefault() ); events.setPager( pager ); } List<Event> eventList = eventStore.getEvents( params, organisationUnits ); events.setEvents( eventList ); return events; } @Override public Events getEvents( Collection<String> uids ) { Events events = new Events(); List<ProgramStageInstance> programStageInstances = manager.getByUid( ProgramStageInstance.class, uids ); programStageInstances.forEach( programStageInstance -> events.getEvents().add( convertProgramStageInstance( programStageInstance ) ) ); return events; } @Override public int getAnonymousEventValuesCountLastUpdatedAfter( Date lastSuccessTime ) { EventSearchParams params = buildAnonymousEventsSearchParams( lastSuccessTime ); return eventStore.getEventCount( params, null ); } @Override public Events getAnonymousEventValuesLastUpdatedAfter( Date lastSuccessTime ) { EventSearchParams params = buildAnonymousEventsSearchParams( lastSuccessTime ); Events anonymousEvents = new Events(); List<Event> events = eventStore.getEvents( params, null ); anonymousEvents.setEvents( events ); return anonymousEvents; } private EventSearchParams buildAnonymousEventsSearchParams( Date lastSuccessTime ) { EventSearchParams params = new EventSearchParams(); params.setProgramType( ProgramType.WITHOUT_REGISTRATION ); params.setLastUpdated( lastSuccessTime ); return params; } @Override public EventRows getEventRows( EventSearchParams params ) { List<OrganisationUnit> organisationUnits = new ArrayList<>(); OrganisationUnit orgUnit = params.getOrgUnit(); OrganisationUnitSelectionMode orgUnitSelectionMode = params.getOrgUnitSelectionMode(); if ( params.getOrgUnit() != null ) { if ( OrganisationUnitSelectionMode.DESCENDANTS.equals( orgUnitSelectionMode ) ) { organisationUnits.addAll( organisationUnitService.getOrganisationUnitWithChildren( orgUnit.getUid() ) ); } else if ( OrganisationUnitSelectionMode.CHILDREN.equals( orgUnitSelectionMode ) ) { organisationUnits.add( orgUnit ); organisationUnits.addAll( orgUnit.getChildren() ); } else // SELECTED { organisationUnits.add( orgUnit ); } } EventRows eventRows = new EventRows(); List<EventRow> eventRowList = eventStore.getEventRows( params, organisationUnits ); eventRows.setEventRows( eventRowList ); return eventRows; } @Override public EventSearchParams getFromUrl( String program, String programStage, ProgramStatus programStatus, Boolean followUp, String orgUnit, OrganisationUnitSelectionMode orgUnitSelectionMode, String trackedEntityInstance, Date startDate, Date endDate, EventStatus status, Date lastUpdated, DataElementCategoryOptionCombo attributeCoc, IdSchemes idSchemes, Integer page, Integer pageSize, boolean totalPages, boolean skipPaging, List<Order> orders, boolean includeAttributes, Set<String> events ) { UserCredentials userCredentials = currentUserService.getCurrentUser().getUserCredentials(); EventSearchParams params = new EventSearchParams(); Program pr = programService.getProgram( program ); if ( StringUtils.isNotEmpty( program ) && pr == null ) { throw new IllegalQueryException( "Program is specified but does not exist: " + program ); } ProgramStage ps = programStageService.getProgramStage( programStage ); if ( StringUtils.isNotEmpty( programStage ) && ps == null ) { throw new IllegalQueryException( "Program stage is specified but does not exist: " + programStage ); } OrganisationUnit ou = organisationUnitService.getOrganisationUnit( orgUnit ); if ( StringUtils.isNotEmpty( orgUnit ) && ou == null ) { throw new IllegalQueryException( "Org unit is specified but does not exist: " + orgUnit ); } if ( ou != null && !organisationUnitService.isInUserHierarchy( ou ) ) { if ( !userCredentials.isSuper() && !userCredentials.isAuthorized( "F_TRACKED_ENTITY_INSTANCE_SEARCH_IN_ALL_ORGUNITS" ) ) { throw new IllegalQueryException( "User has no access to organisation unit: " + ou.getUid() ); } } if ( pr != null && !userCredentials.isSuper() && !userCredentials.canAccessProgram( pr ) ) { throw new IllegalQueryException( "User has no access to program: " + pr.getUid() ); } TrackedEntityInstance tei = entityInstanceService.getTrackedEntityInstance( trackedEntityInstance ); if ( StringUtils.isNotEmpty( trackedEntityInstance ) && tei == null ) { throw new IllegalQueryException( "Tracked entity instance is specified but does not exist: " + trackedEntityInstance ); } if ( events == null ) { events = new HashSet<>(); } params.setProgram( pr ); params.setProgramStage( ps ); params.setOrgUnit( ou ); params.setTrackedEntityInstance( tei ); params.setProgramStatus( programStatus ); params.setFollowUp( followUp ); params.setOrgUnitSelectionMode( orgUnitSelectionMode ); params.setStartDate( startDate ); params.setEndDate( endDate ); params.setEventStatus( status ); params.setLastUpdated( lastUpdated ); params.setCategoryOptionCombo( attributeCoc ); params.setIdSchemes( idSchemes ); params.setPage( page ); params.setPageSize( pageSize ); params.setTotalPages( totalPages ); params.setSkipPaging( skipPaging ); params.setIncludeAttributes( includeAttributes ); params.setOrders( orders ); params.setEvents( events ); return params; } @Override public Event getEvent( String uid ) { ProgramStageInstance psi = programStageInstanceService.getProgramStageInstance( uid ); return psi != null ? convertProgramStageInstance( psi ) : null; } @Override public Event getEvent( ProgramStageInstance programStageInstance ) { return convertProgramStageInstance( programStageInstance ); } // ------------------------------------------------------------------------- // UPDATE // ------------------------------------------------------------------------- @Override public ImportSummaries updateEvents( List<Event> events, boolean singleValue ) { ImportSummaries importSummaries = new ImportSummaries(); int counter = 0; User user = currentUserService.getCurrentUser(); for ( Event event : events ) { importSummaries.addImportSummary( updateEvent( event, user, singleValue, null ) ); if ( counter % FLUSH_FREQUENCY == 0 ) { dbmsManager.clearSession(); } counter++; } return importSummaries; } @Override public ImportSummary updateEvent( Event event, boolean singleValue ) { return updateEvent( event, singleValue, null ); } @Override public ImportSummary updateEvent( Event event, boolean singleValue, ImportOptions importOptions ) { return updateEvent( event, currentUserService.getCurrentUser(), singleValue, importOptions ); } private ImportSummary updateEvent( Event event, User user, boolean singleValue, ImportOptions importOptions ) { if ( importOptions == null ) { importOptions = new ImportOptions(); } ImportSummary importSummary = new ImportSummary(); ProgramStageInstance programStageInstance = programStageInstanceService .getProgramStageInstance( event.getEvent() ); if ( programStageInstance == null ) { importSummary.getConflicts().add( new ImportConflict( "Invalid Event ID.", event.getEvent() ) ); return importSummary.incrementIgnored(); } OrganisationUnit organisationUnit = getOrganisationUnit( importOptions.getIdSchemes(), event.getOrgUnit() ); if ( organisationUnit == null ) { organisationUnit = programStageInstance.getOrganisationUnit(); } Date executionDate = new Date(); if ( event.getEventDate() != null ) { executionDate = DateUtils.parseDate( event.getEventDate() ); programStageInstance.setExecutionDate( executionDate ); } Date dueDate = new Date(); if ( event.getDueDate() != null ) { dueDate = DateUtils.parseDate( event.getDueDate() ); } String storedBy = getStoredBy( event, null, user ); programStageInstance.setStoredBy( storedBy ); String completedBy = getCompletedBy( event, null, user ); if ( event.getStatus() == EventStatus.ACTIVE ) { programStageInstance.setStatus( EventStatus.ACTIVE ); programStageInstance.setCompletedBy( null ); programStageInstance.setCompletedDate( null ); } else if ( programStageInstance.getStatus() != event.getStatus() && event.getStatus() == EventStatus.COMPLETED ) { programStageInstance.setStatus( EventStatus.COMPLETED ); programStageInstance.setCompletedBy( completedBy ); programStageInstance.setCompletedDate( executionDate ); if ( programStageInstance.isCompleted() ) { programStageInstanceService.completeProgramStageInstance( programStageInstance, importOptions.isSkipNotifications(), i18nManager.getI18nFormat() ); } } else if ( event.getStatus() == EventStatus.SKIPPED ) { programStageInstance.setStatus( EventStatus.SKIPPED ); } else if ( event.getStatus() == EventStatus.SCHEDULE ) { programStageInstance.setStatus( EventStatus.SCHEDULE ); } programStageInstance.setDueDate( dueDate ); programStageInstance.setOrganisationUnit( organisationUnit ); if ( !singleValue ) { if ( programStageInstance.getProgramStage().getCaptureCoordinates() && event.getCoordinate().isValid() ) { programStageInstance.setLatitude( event.getCoordinate().getLatitude() ); programStageInstance.setLongitude( event.getCoordinate().getLongitude() ); } else { programStageInstance.setLatitude( null ); programStageInstance.setLongitude( null ); } } Program program = getProgram( importOptions.getIdSchemes().getProgramIdScheme(), event.getProgram() ); validateExpiryDays( event, program, programStageInstance ); programStageInstanceService.updateProgramStageInstance( programStageInstance ); saveTrackedEntityComment( programStageInstance, event, storedBy ); Set<TrackedEntityDataValue> dataValues = new HashSet<>( dataValueService.getTrackedEntityDataValues( programStageInstance ) ); Map<String, TrackedEntityDataValue> existingDataValues = getDataElementDataValueMap( dataValues ); if ( programStageInstance.getProgramStage().getCaptureCoordinates() ) { Coordinate coordinate = null; if ( programStageInstance.getLongitude() != null && programStageInstance.getLatitude() != null ) { coordinate = new Coordinate( programStageInstance.getLongitude(), programStageInstance.getLatitude() ); try { List<Double> list = OBJECT_MAPPER.readValue( coordinate.getCoordinateString(), new TypeReference<List<Double>>() { } ); coordinate.setLongitude( list.get( 0 ) ); coordinate.setLatitude( list.get( 1 ) ); } catch ( IOException ignored ) { } } if ( coordinate != null && coordinate.isValid() ) { event.setCoordinate( coordinate ); } } for ( DataValue value : event.getDataValues() ) { DataElement dataElement = getDataElement( importOptions.getIdSchemes().getDataElementIdScheme(), value.getDataElement() ); TrackedEntityDataValue dataValue = dataValueService.getTrackedEntityDataValue( programStageInstance, dataElement ); if ( !validateDataValue( dataElement, value.getValue(), importSummary ) ) { continue; } if ( dataValue != null ) { if ( StringUtils.isEmpty( value.getValue() ) && dataElement.isFileType() && !StringUtils.isEmpty( dataValue.getValue() ) ) { fileResourceService.deleteFileResource( dataValue.getValue() ); } dataValue.setValue( value.getValue() ); dataValue.setProvidedElsewhere( value.getProvidedElsewhere() ); dataValueService.updateTrackedEntityDataValue( dataValue ); dataValues.remove( dataValue ); } else { TrackedEntityDataValue existingDataValue = existingDataValues.get( value.getDataElement() ); saveDataValue( programStageInstance, event.getStoredBy(), dataElement, value.getValue(), value.getProvidedElsewhere(), existingDataValue, null ); } } if ( !singleValue ) { dataValues.forEach( dataValueService::deleteTrackedEntityDataValue ); } return importSummary; } @Override public void updateEventForNote( Event event ) { ProgramStageInstance programStageInstance = programStageInstanceService .getProgramStageInstance( event.getEvent() ); if ( programStageInstance == null ) { return; } saveTrackedEntityComment( programStageInstance, event, getStoredBy( event, null, currentUserService.getCurrentUser() ) ); } @Override public void updateEventForEventDate( Event event ) { ProgramStageInstance programStageInstance = programStageInstanceService .getProgramStageInstance( event.getEvent() ); if ( programStageInstance == null ) { return; } Date executionDate = new Date(); if ( event.getEventDate() != null ) { executionDate = DateUtils.parseDate( event.getEventDate() ); } if ( event.getStatus() == EventStatus.COMPLETED ) { programStageInstance.setStatus( EventStatus.COMPLETED ); } else { programStageInstance.setStatus( EventStatus.VISITED ); } ImportOptions importOptions = new ImportOptions(); OrganisationUnit organisationUnit = getOrganisationUnit( importOptions.getIdSchemes(), event.getOrgUnit() ); if ( organisationUnit == null ) { organisationUnit = programStageInstance.getOrganisationUnit(); } programStageInstance.setOrganisationUnit( organisationUnit ); programStageInstance.setExecutionDate( executionDate ); programStageInstanceService.updateProgramStageInstance( programStageInstance ); } // ------------------------------------------------------------------------- // DELETE // ------------------------------------------------------------------------- @Override public ImportSummary deleteEvent( String uid ) { ProgramStageInstance programStageInstance = programStageInstanceService.getProgramStageInstance( uid ); if ( programStageInstance != null ) { programStageInstanceService.deleteProgramStageInstance( programStageInstance ); return new ImportSummary( ImportStatus.SUCCESS, "Deletion of event " + uid + " was successful" ) .incrementDeleted(); } return new ImportSummary( ImportStatus.ERROR, "ID " + uid + " does not point to a valid event: " + uid ) .incrementIgnored(); } @Override public ImportSummaries deleteEvents( List<String> uids ) { ImportSummaries importSummaries = new ImportSummaries(); int counter = 0; for ( String uid : uids ) { importSummaries.addImportSummary( deleteEvent( uid ) ); if ( counter % FLUSH_FREQUENCY == 0 ) { dbmsManager.clearSession(); } counter++; } return importSummaries; } // ------------------------------------------------------------------------- // HELPERS // ------------------------------------------------------------------------- private Event convertProgramStageInstance( ProgramStageInstance programStageInstance ) { if ( programStageInstance == null ) { return null; } Event event = new Event(); event.setEvent( programStageInstance.getUid() ); if ( programStageInstance.getProgramInstance().getEntityInstance() != null ) { event.setTrackedEntityInstance( programStageInstance.getProgramInstance().getEntityInstance().getUid() ); } event.setFollowup( programStageInstance.getProgramInstance().getFollowup() ); event.setEnrollmentStatus( EnrollmentStatus.fromProgramStatus( programStageInstance.getProgramInstance().getStatus() ) ); event.setStatus( programStageInstance.getStatus() ); event.setEventDate( DateUtils.getIso8601NoTz( programStageInstance.getExecutionDate() ) ); event.setDueDate( DateUtils.getIso8601NoTz( programStageInstance.getDueDate() ) ); event.setStoredBy( programStageInstance.getStoredBy() ); event.setCompletedBy( programStageInstance.getCompletedBy() ); event.setCompletedDate( DateUtils.getIso8601NoTz( programStageInstance.getCompletedDate() ) ); event.setCreated( DateUtils.getIso8601NoTz( programStageInstance.getCreated() ) ); event.setLastUpdated( DateUtils.getIso8601NoTz( programStageInstance.getLastUpdated() ) ); UserCredentials userCredentials = currentUserService.getCurrentUser().getUserCredentials(); OrganisationUnit ou = programStageInstance.getOrganisationUnit(); if ( ou != null ) { if ( !organisationUnitService.isInUserHierarchy( ou ) ) { if ( !userCredentials.isSuper() && !userCredentials.isAuthorized( "F_TRACKED_ENTITY_INSTANCE_SEARCH_IN_ALL_ORGUNITS" ) ) { throw new IllegalQueryException( "User has no access to organisation unit: " + ou.getUid() ); } } event.setOrgUnit( ou.getUid() ); } Program program = programStageInstance.getProgramInstance().getProgram(); if ( !userCredentials.isSuper() && !userCredentials.getAllPrograms().contains( program ) ) { throw new IllegalQueryException( "User has no access to program: " + program.getUid() ); } event.setProgram( program.getUid() ); event.setEnrollment( programStageInstance.getProgramInstance().getUid() ); event.setProgramStage( programStageInstance.getProgramStage().getUid() ); if ( programStageInstance.getProgramInstance().getEntityInstance() != null ) { event.setTrackedEntityInstance( programStageInstance.getProgramInstance().getEntityInstance().getUid() ); } if ( programStageInstance.getProgramStage().getCaptureCoordinates() ) { Coordinate coordinate = null; if ( programStageInstance.getLongitude() != null && programStageInstance.getLatitude() != null ) { coordinate = new Coordinate( programStageInstance.getLongitude(), programStageInstance.getLatitude() ); try { List<Double> list = OBJECT_MAPPER.readValue( coordinate.getCoordinateString(), new TypeReference<List<Double>>() { } ); coordinate.setLongitude( list.get( 0 ) ); coordinate.setLatitude( list.get( 1 ) ); } catch ( IOException ignored ) { } } if ( coordinate != null && coordinate.isValid() ) { event.setCoordinate( coordinate ); } } Collection<TrackedEntityDataValue> dataValues = dataValueService .getTrackedEntityDataValues( programStageInstance ); for ( TrackedEntityDataValue dataValue : dataValues ) { DataValue value = new DataValue(); value.setCreated( DateUtils.getIso8601NoTz( dataValue.getCreated() ) ); value.setLastUpdated( DateUtils.getIso8601NoTz( dataValue.getLastUpdated() ) ); value.setDataElement( dataValue.getDataElement().getUid() ); value.setValue( dataValue.getValue() ); value.setProvidedElsewhere( dataValue.getProvidedElsewhere() ); value.setStoredBy( dataValue.getStoredBy() ); event.getDataValues().add( value ); } List<TrackedEntityComment> comments = programStageInstance.getComments(); for ( TrackedEntityComment comment : comments ) { Note note = new Note(); note.setValue( comment.getCommentText() ); note.setStoredBy( comment.getCreator() ); if ( comment.getCreatedDate() != null ) { note.setStoredDate( DateUtils.getIso8601NoTz( comment.getCreatedDate() ) ); } event.getNotes().add( note ); } return event; } private boolean canAccess( Program program, User user ) { if ( accessibleProgramsCache.isEmpty() ) { accessibleProgramsCache = programService.getUserPrograms( user ); } return accessibleProgramsCache.contains( program ); } private boolean validateDataValue( DataElement dataElement, String value, ImportSummary importSummary ) { String status = ValidationUtils.dataValueIsValid( value, dataElement ); if ( status != null ) { importSummary.getConflicts().add( new ImportConflict( dataElement.getUid(), status ) ); importSummary.getImportCount().incrementIgnored(); return false; } return true; } private ImportSummary saveEvent( Program program, ProgramInstance programInstance, ProgramStage programStage, ProgramStageInstance programStageInstance, OrganisationUnit organisationUnit, Event event, User user, ImportOptions importOptions ) { Assert.notNull( program ); Assert.notNull( programInstance ); Assert.notNull( programStage ); ImportSummary importSummary = new ImportSummary(); importSummary.setStatus( ImportStatus.SUCCESS ); if ( importOptions == null ) { importOptions = new ImportOptions(); } boolean existingEvent = programStageInstance != null; boolean dryRun = importOptions.isDryRun(); Date executionDate = null; // = new Date(); if ( event.getEventDate() != null ) { executionDate = DateUtils.parseDate( event.getEventDate() ); } Date dueDate = new Date(); if ( event.getDueDate() != null ) { dueDate = DateUtils.parseDate( event.getDueDate() ); } String storedBy = getStoredBy( event, importSummary, user ); String completedBy = getCompletedBy( event, importSummary, user ); DataElementCategoryOptionCombo coc = null; if ( event.getAttributeCategoryOptions() != null && program.getCategoryCombo() != null ) { IdScheme idScheme = importOptions.getIdSchemes().getCategoryOptionIdScheme(); try { coc = inputUtils.getAttributeOptionCombo( program.getCategoryCombo(), event.getAttributeCategoryOptions(), idScheme ); } catch ( IllegalQueryException ex ) { importSummary.getConflicts() .add( new ImportConflict( ex.getMessage(), event.getAttributeCategoryOptions() ) ); } } else { coc = categoryService.getDefaultDataElementCategoryOptionCombo(); } if ( !dryRun ) { if ( programStageInstance == null ) { programStageInstance = createProgramStageInstance( programStage, programInstance, organisationUnit, dueDate, executionDate, event.getStatus().getValue(), event.getCoordinate(), completedBy, event.getEvent(), coc, importOptions ); } else { updateProgramStageInstance( programStage, programInstance, organisationUnit, dueDate, executionDate, event.getStatus().getValue(), event.getCoordinate(), completedBy, programStageInstance, coc, importOptions ); } saveTrackedEntityComment( programStageInstance, event, storedBy ); importSummary.setReference( programStageInstance.getUid() ); } Map<String, TrackedEntityDataValue> dataElementValueMap = Maps.newHashMap(); if ( existingEvent ) { dataElementValueMap = getDataElementDataValueMap( dataValueService.getTrackedEntityDataValues( programStageInstance ) ); } for ( DataValue dataValue : event.getDataValues() ) { DataElement dataElement; if ( dataElementValueMap.containsKey( dataValue.getDataElement() ) ) { dataElement = dataElementValueMap.get( dataValue.getDataElement() ).getDataElement(); } else { dataElement = getDataElement( importOptions.getIdSchemes().getDataElementIdScheme(), dataValue.getDataElement() ); } if ( dataElement != null ) { if ( validateDataValue( dataElement, dataValue.getValue(), importSummary ) ) { String dataValueStoredBy = dataValue.getStoredBy() != null ? dataValue.getStoredBy() : storedBy; if ( !dryRun ) { TrackedEntityDataValue existingDataValue = dataElementValueMap .get( dataValue.getDataElement() ); saveDataValue( programStageInstance, dataValueStoredBy, dataElement, dataValue.getValue(), dataValue.getProvidedElsewhere(), existingDataValue, importSummary ); } } } else { importSummary.getConflicts().add( new ImportConflict( "dataElement", dataValue.getDataElement() + " is not a valid data element" ) ); importSummary.getImportCount().incrementIgnored(); } } return importSummary; } private void saveDataValue( ProgramStageInstance programStageInstance, String storedBy, DataElement dataElement, String value, Boolean providedElsewhere, TrackedEntityDataValue dataValue, ImportSummary importSummary ) { if ( value != null && value.trim().length() == 0 ) { value = null; } if ( value != null ) { if ( dataValue == null ) { dataValue = new TrackedEntityDataValue( programStageInstance, dataElement, value ); dataValue.setStoredBy( storedBy ); dataValue.setProvidedElsewhere( providedElsewhere ); dataValueService.saveTrackedEntityDataValue( dataValue ); if ( importSummary != null ) { importSummary.getImportCount().incrementImported(); } } else { dataValue.setValue( value ); dataValue.setStoredBy( storedBy ); dataValue.setProvidedElsewhere( providedElsewhere ); dataValueService.updateTrackedEntityDataValue( dataValue ); if ( importSummary != null ) { importSummary.getImportCount().incrementUpdated(); } } } else if ( dataValue != null ) { dataValueService.deleteTrackedEntityDataValue( dataValue ); if ( importSummary != null ) { importSummary.getImportCount().incrementDeleted(); } } } private ProgramStageInstance createProgramStageInstance( ProgramStage programStage, ProgramInstance programInstance, OrganisationUnit organisationUnit, Date dueDate, Date executionDate, int status, Coordinate coordinate, String completedBy, String programStageInstanceUid, DataElementCategoryOptionCombo coc, ImportOptions importOptions ) { ProgramStageInstance programStageInstance = new ProgramStageInstance(); programStageInstance.setUid( CodeGenerator.isValidCode( programStageInstanceUid ) ? programStageInstanceUid : CodeGenerator.generateCode() ); updateProgramStageInstance( programStage, programInstance, organisationUnit, dueDate, executionDate, status, coordinate, completedBy, programStageInstance, coc, importOptions ); return programStageInstance; } private void updateProgramStageInstance( ProgramStage programStage, ProgramInstance programInstance, OrganisationUnit organisationUnit, Date dueDate, Date executionDate, int status, Coordinate coordinate, String completedBy, ProgramStageInstance programStageInstance, DataElementCategoryOptionCombo coc, ImportOptions importOptions ) { programStageInstance.setProgramInstance( programInstance ); programStageInstance.setProgramStage( programStage ); programStageInstance.setDueDate( dueDate ); programStageInstance.setExecutionDate( executionDate ); programStageInstance.setOrganisationUnit( organisationUnit ); programStageInstance.setAttributeOptionCombo( coc ); if ( programStage.getCaptureCoordinates() ) { if ( coordinate != null && coordinate.isValid() ) { programStageInstance.setLongitude( coordinate.getLongitude() ); programStageInstance.setLatitude( coordinate.getLatitude() ); } } programStageInstance.setStatus( EventStatus.fromInt( status ) ); if ( programStageInstance.getId() == 0 ) { programStageInstance.setAutoFields(); sessionFactory.getCurrentSession().save( programStageInstance ); } else { sessionFactory.getCurrentSession().update( programStageInstance ); sessionFactory.getCurrentSession().refresh( programStageInstance ); } if ( programStageInstance.isCompleted() ) { programStageInstance.setStatus( EventStatus.COMPLETED ); programStageInstance.setCompletedDate( new Date() ); programStageInstance.setCompletedBy( completedBy ); programStageInstanceService.completeProgramStageInstance( programStageInstance, importOptions.isSkipNotifications(), i18nManager.getI18nFormat() ); } } private void saveTrackedEntityComment( ProgramStageInstance programStageInstance, Event event, String storedBy ) { for ( Note note : event.getNotes() ) { TrackedEntityComment comment = new TrackedEntityComment(); comment.setCreator( storedBy ); comment.setCreatedDate( new Date() ); comment.setCommentText( note.getValue() ); commentService.addTrackedEntityComment( comment ); programStageInstance.getComments().add( comment ); programStageInstanceService.updateProgramStageInstance( programStageInstance ); } } private String getCompletedBy( Event event, ImportSummary importSummary, User fallbackUser ) { String completedBy = event.getCompletedBy(); if ( completedBy == null ) { completedBy = User.getSafeUsername( fallbackUser ); } else if ( completedBy.length() >= 31 ) { if ( importSummary != null ) { importSummary.getConflicts().add( new ImportConflict( "completed by", completedBy + " is more than 31 characters, using current username instead" ) ); } completedBy = User.getSafeUsername( fallbackUser ); } return completedBy; } private String getStoredBy( Event event, ImportSummary importSummary, User fallbackUser ) { String storedBy = event.getStoredBy(); if ( storedBy == null ) { storedBy = User.getSafeUsername( fallbackUser ); } else if ( storedBy.length() >= 31 ) { if ( importSummary != null ) { importSummary.getConflicts().add( new ImportConflict( "stored by", storedBy + " is more than 31 characters, using current username instead" ) ); } storedBy = User.getSafeUsername( fallbackUser ); } return storedBy; } private Map<String, TrackedEntityDataValue> getDataElementDataValueMap( Collection<TrackedEntityDataValue> dataValues ) { return dataValues.stream().collect( Collectors.toMap( dv -> dv.getDataElement().getUid(), dv -> dv ) ); } private OrganisationUnit getOrganisationUnit( IdSchemes idSchemes, String id ) { return organisationUnitCache.get( id, new IdentifiableObjectCallable<>( manager, OrganisationUnit.class, idSchemes.getOrgUnitIdScheme(), id ) ); } private Program getProgram( IdScheme idScheme, String id ) { return programCache.get( id, new IdentifiableObjectCallable<>( manager, Program.class, idScheme, id ) ); } private ProgramStage getProgramStage( IdScheme idScheme, String id ) { return programStageCache.get( id, new IdentifiableObjectCallable<>( manager, ProgramStage.class, idScheme, id ) ); } private DataElement getDataElement( IdScheme idScheme, String id ) { return dataElementCache.get( id, new IdentifiableObjectCallable<>( manager, DataElement.class, idScheme, id ) ); } @Override public void validate( EventSearchParams params ) throws IllegalQueryException { String violation = null; if ( params == null ) { throw new IllegalQueryException( "Query parameters can not be empty." ); } if ( params.getProgram() == null && params.getOrgUnit() == null && params.getTrackedEntityInstance() == null && params.getEvents().isEmpty() ) { violation = "At least one of the following query parameters are required: orgUnit, program, trackedEntityInstance or event."; } if ( violation != null ) { log.warn( "Validation failed: " + violation ); throw new IllegalQueryException( violation ); } } private void validateExpiryDays( Event event, Program program, ProgramStageInstance programStageInstance ) { if ( program != null ) { if ( program.getCompleteEventsExpiryDays() > 0 ) { if ( event.getStatus() == EventStatus.COMPLETED || programStageInstance != null && programStageInstance.getStatus() == EventStatus.COMPLETED ) { Date referenceDate = null; if ( programStageInstance != null ) { referenceDate = programStageInstance.getCompletedDate(); } else { if ( event.getCompletedDate() != null ) { referenceDate = DateUtils.parseDate( event.getCompletedDate() ); } } if ( referenceDate == null ) { throw new IllegalQueryException( "Event needs to have completed date." ); } if ( (new Date()).after( DateUtils.getDateAfterAddition( referenceDate, program.getCompleteEventsExpiryDays() ) ) ) { throw new IllegalQueryException( "The event's completness date has expired. Not possible to make changes to this event" ); } } } PeriodType periodType = program.getExpiryPeriodType(); if ( periodType != null && program.getExpiryDays() > 0 ) { if ( programStageInstance != null ) { Date today = new Date(); if ( programStageInstance.getExecutionDate() == null ) { throw new IllegalQueryException( "Event needs to have event date." ); } Period period = periodType.createPeriod( programStageInstance.getExecutionDate() ); if ( today.after( DateUtils.getDateAfterAddition( period.getEndDate(), program.getExpiryDays() ) ) ) { throw new IllegalQueryException( "The program's expiry date has passed. It is not possible to make changes to this event." ); } } else { String referenceDate = event.getEventDate() != null ? event.getEventDate() : event.getDueDate() != null ? event.getDueDate() : null; if ( referenceDate == null ) { throw new IllegalQueryException( "Event needs to have at least one (event or schedule) date. " ); } Period period = periodType.createPeriod( new Date() ); if ( DateUtils.parseDate( referenceDate ).before( period.getStartDate() ) ) { throw new IllegalQueryException( "The event's date belongs to an expired period. It is not possble to create such event." ); } } } } } }
dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/events/event/AbstractEventService.java
package org.hisp.dhis.dxf2.events.event; /* * Copyright (c) 2004-2016, University of Oslo * 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 HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.SessionFactory; import org.hisp.dhis.common.CodeGenerator; import org.hisp.dhis.common.IdScheme; import org.hisp.dhis.common.IdSchemes; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.common.IllegalQueryException; import org.hisp.dhis.common.OrganisationUnitSelectionMode; import org.hisp.dhis.common.Pager; import org.hisp.dhis.commons.collection.CachingMap; import org.hisp.dhis.commons.util.DebugUtils; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo; import org.hisp.dhis.dataelement.DataElementCategoryService; import org.hisp.dhis.dataelement.DataElementService; import org.hisp.dhis.dbms.DbmsManager; import org.hisp.dhis.dxf2.common.ImportOptions; import org.hisp.dhis.dxf2.events.enrollment.EnrollmentStatus; import org.hisp.dhis.dxf2.events.report.EventRow; import org.hisp.dhis.dxf2.events.report.EventRows; import org.hisp.dhis.dxf2.importsummary.ImportConflict; import org.hisp.dhis.dxf2.importsummary.ImportStatus; import org.hisp.dhis.dxf2.importsummary.ImportSummaries; import org.hisp.dhis.dxf2.importsummary.ImportSummary; import org.hisp.dhis.dxf2.utils.InputUtils; import org.hisp.dhis.event.EventStatus; import org.hisp.dhis.fileresource.FileResourceService; import org.hisp.dhis.i18n.I18nManager; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.organisationunit.OrganisationUnitService; import org.hisp.dhis.period.Period; import org.hisp.dhis.period.PeriodType; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramInstance; import org.hisp.dhis.program.ProgramInstanceService; import org.hisp.dhis.program.ProgramService; import org.hisp.dhis.program.ProgramStage; import org.hisp.dhis.program.ProgramStageInstance; import org.hisp.dhis.program.ProgramStageInstanceService; import org.hisp.dhis.program.ProgramStageService; import org.hisp.dhis.program.ProgramStatus; import org.hisp.dhis.program.ProgramType; import org.hisp.dhis.query.Order; import org.hisp.dhis.scheduling.TaskId; import org.hisp.dhis.system.callable.IdentifiableObjectCallable; import org.hisp.dhis.system.notification.NotificationLevel; import org.hisp.dhis.system.notification.Notifier; import org.hisp.dhis.system.util.DateUtils; import org.hisp.dhis.system.util.ValidationUtils; import org.hisp.dhis.trackedentity.TrackedEntityInstance; import org.hisp.dhis.trackedentity.TrackedEntityInstanceService; import org.hisp.dhis.trackedentitycomment.TrackedEntityComment; import org.hisp.dhis.trackedentitycomment.TrackedEntityCommentService; import org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValue; import org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValueService; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.User; import org.hisp.dhis.user.UserCredentials; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static org.hisp.dhis.system.notification.NotificationLevel.ERROR; /** * @author Morten Olav Hansen <mortenoh@gmail.com> */ @Transactional public abstract class AbstractEventService implements EventService { private static final Log log = LogFactory.getLog( AbstractEventService.class ); // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- @Autowired protected ProgramService programService; @Autowired protected ProgramStageService programStageService; @Autowired protected ProgramInstanceService programInstanceService; @Autowired protected ProgramStageInstanceService programStageInstanceService; @Autowired protected OrganisationUnitService organisationUnitService; @Autowired protected DataElementService dataElementService; @Autowired protected CurrentUserService currentUserService; @Autowired protected TrackedEntityDataValueService dataValueService; @Autowired protected TrackedEntityInstanceService entityInstanceService; @Autowired protected TrackedEntityCommentService commentService; @Autowired protected EventStore eventStore; @Autowired protected I18nManager i18nManager; @Autowired protected Notifier notifier; @Autowired protected SessionFactory sessionFactory; @Autowired protected DbmsManager dbmsManager; @Autowired protected IdentifiableObjectManager manager; @Autowired protected DataElementCategoryService categoryService; @Autowired protected InputUtils inputUtils; @Autowired protected FileResourceService fileResourceService; protected static final int FLUSH_FREQUENCY = 20; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); // ------------------------------------------------------------------------- // Caches // ------------------------------------------------------------------------- private CachingMap<String, OrganisationUnit> organisationUnitCache = new CachingMap<>(); private CachingMap<String, Program> programCache = new CachingMap<>(); private CachingMap<String, ProgramStage> programStageCache = new CachingMap<>(); private CachingMap<String, DataElement> dataElementCache = new CachingMap<>(); private Set<Program> accessibleProgramsCache = new HashSet<>(); // ------------------------------------------------------------------------- // CREATE // ------------------------------------------------------------------------- @Override public ImportSummaries addEvents( List<Event> events, ImportOptions importOptions ) { ImportSummaries importSummaries = new ImportSummaries(); int counter = 0; User user = currentUserService.getCurrentUser(); for ( Event event : events ) { importSummaries.addImportSummary( addEvent( event, user, importOptions ) ); if ( counter % FLUSH_FREQUENCY == 0 ) { dbmsManager.clearSession(); } counter++; } return importSummaries; } @Override public ImportSummaries addEvents( List<Event> events, ImportOptions importOptions, TaskId taskId ) { notifier.clear( taskId ).notify( taskId, "Importing events" ); try { ImportSummaries importSummaries = addEvents( events, importOptions ); if ( taskId != null ) { notifier.notify( taskId, NotificationLevel.INFO, "Import done", true ).addTaskSummary( taskId, importSummaries ); } return importSummaries; } catch ( RuntimeException ex ) { log.error( DebugUtils.getStackTrace( ex ) ); notifier.notify( taskId, ERROR, "Process failed: " + ex.getMessage(), true ); return new ImportSummaries().addImportSummary( new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() ) ); } } @Override public ImportSummary addEvent( Event event, ImportOptions importOptions ) { return addEvent( event, currentUserService.getCurrentUser(), importOptions ); } protected ImportSummary addEvent( Event event, User user, ImportOptions importOptions ) { if ( importOptions == null ) { importOptions = new ImportOptions(); } Program program = getProgram( importOptions.getIdSchemes().getProgramIdScheme(), event.getProgram() ); ProgramStage programStage = getProgramStage( importOptions.getIdSchemes().getProgramStageIdScheme(), event.getProgramStage() ); ProgramInstance programInstance; ProgramStageInstance programStageInstance = null; if ( program == null ) { return new ImportSummary( ImportStatus.ERROR, "Event.program does not point to a valid program: " + event.getProgram() ).incrementIgnored(); } if ( programStage == null && program.isRegistration() ) { return new ImportSummary( ImportStatus.ERROR, "Event.programStage does not point to a valid programStage, and program is multi stage: " + event.getProgramStage() ).incrementIgnored(); } else if ( programStage == null ) { programStage = program.getProgramStageByStage( 1 ); } Assert.notNull( program ); Assert.notNull( programStage ); if ( !canAccess( program, user ) ) { return new ImportSummary( ImportStatus.ERROR, "Current user does not have permission to access this program" ).incrementIgnored(); } if ( program.isRegistration() ) { if ( event.getTrackedEntityInstance() == null ) { return new ImportSummary( ImportStatus.ERROR, "No Event.trackedEntityInstance was provided for registration based program" ).incrementIgnored(); } org.hisp.dhis.trackedentity.TrackedEntityInstance entityInstance = entityInstanceService .getTrackedEntityInstance( event.getTrackedEntityInstance() ); if ( entityInstance == null ) { return new ImportSummary( ImportStatus.ERROR, "Event.trackedEntityInstance does not point to a valid tracked entity instance: " + event.getTrackedEntityInstance() ).incrementIgnored(); } List<ProgramInstance> programInstances = new ArrayList<>( programInstanceService.getProgramInstances( entityInstance, program, ProgramStatus.ACTIVE ) ); if ( programInstances.isEmpty() ) { return new ImportSummary( ImportStatus.ERROR, "Tracked entity instance: " + entityInstance.getUid() + " is not enrolled in program: " + program.getUid() ).incrementIgnored(); } else if ( programInstances.size() > 1 ) { return new ImportSummary( ImportStatus.ERROR, "Tracked entity instance: " + entityInstance.getUid() + " have multiple active enrollments in program: " + program.getUid() ).incrementIgnored(); } programInstance = programInstances.get( 0 ); if ( !programStage.getRepeatable() ) { programStageInstance = programStageInstanceService.getProgramStageInstance( programInstance, programStage ); if ( programStageInstance != null ) { return new ImportSummary( ImportStatus.ERROR, "Program stage is not repeatable and an event already exists" ).incrementIgnored(); } } else { if ( event.getEvent() != null ) { programStageInstance = programStageInstanceService.getProgramStageInstance( event.getEvent() ); if ( programStageInstance == null ) { if ( !CodeGenerator.isValidCode( event.getEvent() ) ) { return new ImportSummary( ImportStatus.ERROR, "Event.event did not point to a valid event: " + event.getEvent() ).incrementIgnored(); } } } } } else { List<ProgramInstance> programInstances = new ArrayList<>( programInstanceService.getProgramInstances( program, ProgramStatus.ACTIVE ) ); if ( programInstances.isEmpty() ) { // Create PI if it doesn't exist (should only be one) ProgramInstance pi = new ProgramInstance(); pi.setEnrollmentDate( new Date() ); pi.setIncidentDate( new Date() ); pi.setProgram( program ); pi.setStatus( ProgramStatus.ACTIVE ); programInstanceService.addProgramInstance( pi ); programInstances.add( pi ); } else if ( programInstances.size() > 1 ) { return new ImportSummary( ImportStatus.ERROR, "Multiple active program instances exists for program: " + program.getUid() ).incrementIgnored(); } programInstance = programInstances.get( 0 ); if ( event.getEvent() != null ) { programStageInstance = programStageInstanceService.getProgramStageInstance( event.getEvent() ); if ( programStageInstance == null ) { if ( !CodeGenerator.isValidCode( event.getEvent() ) ) { return new ImportSummary( ImportStatus.ERROR, "Event.event did not point to a valid event: " + event.getEvent() ).incrementIgnored(); } } } } OrganisationUnit organisationUnit = getOrganisationUnit( importOptions.getIdSchemes(), event.getOrgUnit() ); if ( organisationUnit == null ) { return new ImportSummary( ImportStatus.ERROR, "Event.orgUnit does not point to a valid organisation unit: " + event.getOrgUnit() ).incrementIgnored(); } if ( !program.hasOrganisationUnit( organisationUnit ) ) { return new ImportSummary( ImportStatus.ERROR, "Program is not assigned to this organisation unit: " + event.getOrgUnit() ).incrementIgnored(); } validateExpiryDays( event, program, null ); return saveEvent( program, programInstance, programStage, programStageInstance, organisationUnit, event, user, importOptions ); } // ------------------------------------------------------------------------- // READ // ------------------------------------------------------------------------- @Override public Events getEvents( EventSearchParams params ) { validate( params ); List<OrganisationUnit> organisationUnits = new ArrayList<>(); OrganisationUnit orgUnit = params.getOrgUnit(); OrganisationUnitSelectionMode orgUnitSelectionMode = params.getOrgUnitSelectionMode(); if ( params.getOrgUnit() != null ) { if ( OrganisationUnitSelectionMode.DESCENDANTS.equals( orgUnitSelectionMode ) ) { organisationUnits.addAll( organisationUnitService.getOrganisationUnitWithChildren( orgUnit.getUid() ) ); } else if ( OrganisationUnitSelectionMode.CHILDREN.equals( orgUnitSelectionMode ) ) { organisationUnits.add( orgUnit ); organisationUnits.addAll( orgUnit.getChildren() ); } else // SELECTED { organisationUnits.add( orgUnit ); } } if ( !params.isPaging() && !params.isSkipPaging() ) { params.setDefaultPaging(); } Events events = new Events(); if ( params.isPaging() ) { int count = 0; if ( params.isTotalPages() ) { count = eventStore.getEventCount( params, organisationUnits ); } Pager pager = new Pager( params.getPageWithDefault(), count, params.getPageSizeWithDefault() ); events.setPager( pager ); } List<Event> eventList = eventStore.getEvents( params, organisationUnits ); events.setEvents( eventList ); return events; } @Override public Events getEvents( Collection<String> uids ) { Events events = new Events(); List<ProgramStageInstance> programStageInstances = manager.getByUid( ProgramStageInstance.class, uids ); programStageInstances.forEach( programStageInstance -> events.getEvents().add( convertProgramStageInstance( programStageInstance ) ) ); return events; } @Override public int getAnonymousEventValuesCountLastUpdatedAfter( Date lastSuccessTime ) { EventSearchParams params = buildAnonymousEventsSearchParams( lastSuccessTime ); return eventStore.getEventCount( params, null ); } @Override public Events getAnonymousEventValuesLastUpdatedAfter( Date lastSuccessTime ) { EventSearchParams params = buildAnonymousEventsSearchParams( lastSuccessTime ); Events anonymousEvents = new Events(); List<Event> events = eventStore.getEvents( params, null ); anonymousEvents.setEvents( events ); return anonymousEvents; } private EventSearchParams buildAnonymousEventsSearchParams( Date lastSuccessTime ) { EventSearchParams params = new EventSearchParams(); params.setProgramType( ProgramType.WITHOUT_REGISTRATION ); params.setLastUpdated( lastSuccessTime ); return params; } @Override public EventRows getEventRows( EventSearchParams params ) { List<OrganisationUnit> organisationUnits = new ArrayList<>(); OrganisationUnit orgUnit = params.getOrgUnit(); OrganisationUnitSelectionMode orgUnitSelectionMode = params.getOrgUnitSelectionMode(); if ( params.getOrgUnit() != null ) { if ( OrganisationUnitSelectionMode.DESCENDANTS.equals( orgUnitSelectionMode ) ) { organisationUnits.addAll( organisationUnitService.getOrganisationUnitWithChildren( orgUnit.getUid() ) ); } else if ( OrganisationUnitSelectionMode.CHILDREN.equals( orgUnitSelectionMode ) ) { organisationUnits.add( orgUnit ); organisationUnits.addAll( orgUnit.getChildren() ); } else // SELECTED { organisationUnits.add( orgUnit ); } } EventRows eventRows = new EventRows(); List<EventRow> eventRowList = eventStore.getEventRows( params, organisationUnits ); eventRows.setEventRows( eventRowList ); return eventRows; } @Override public EventSearchParams getFromUrl( String program, String programStage, ProgramStatus programStatus, Boolean followUp, String orgUnit, OrganisationUnitSelectionMode orgUnitSelectionMode, String trackedEntityInstance, Date startDate, Date endDate, EventStatus status, Date lastUpdated, DataElementCategoryOptionCombo attributeCoc, IdSchemes idSchemes, Integer page, Integer pageSize, boolean totalPages, boolean skipPaging, List<Order> orders, boolean includeAttributes, Set<String> events ) { UserCredentials userCredentials = currentUserService.getCurrentUser().getUserCredentials(); EventSearchParams params = new EventSearchParams(); Program pr = programService.getProgram( program ); if ( StringUtils.isNotEmpty( program ) && pr == null ) { throw new IllegalQueryException( "Program is specified but does not exist: " + program ); } ProgramStage ps = programStageService.getProgramStage( programStage ); if ( StringUtils.isNotEmpty( programStage ) && ps == null ) { throw new IllegalQueryException( "Program stage is specified but does not exist: " + programStage ); } OrganisationUnit ou = organisationUnitService.getOrganisationUnit( orgUnit ); if ( StringUtils.isNotEmpty( orgUnit ) && ou == null ) { throw new IllegalQueryException( "Org unit is specified but does not exist: " + orgUnit ); } if ( ou != null && !organisationUnitService.isInUserHierarchy( ou ) ) { if ( !userCredentials.isSuper() && !userCredentials.isAuthorized( "F_TRACKED_ENTITY_INSTANCE_SEARCH_IN_ALL_ORGUNITS" ) ) { throw new IllegalQueryException( "User has no access to organisation unit: " + ou.getUid() ); } } if ( pr != null && !userCredentials.isSuper() && !userCredentials.canAccessProgram( pr ) ) { throw new IllegalQueryException( "User has no access to program: " + pr.getUid() ); } TrackedEntityInstance tei = entityInstanceService.getTrackedEntityInstance( trackedEntityInstance ); if ( StringUtils.isNotEmpty( trackedEntityInstance ) && tei == null ) { throw new IllegalQueryException( "Tracked entity instance is specified but does not exist: " + trackedEntityInstance ); } if ( events == null ) { events = new HashSet<>(); } params.setProgram( pr ); params.setProgramStage( ps ); params.setOrgUnit( ou ); params.setTrackedEntityInstance( tei ); params.setProgramStatus( programStatus ); params.setFollowUp( followUp ); params.setOrgUnitSelectionMode( orgUnitSelectionMode ); params.setStartDate( startDate ); params.setEndDate( endDate ); params.setEventStatus( status ); params.setLastUpdated( lastUpdated ); params.setCategoryOptionCombo( attributeCoc ); params.setIdSchemes( idSchemes ); params.setPage( page ); params.setPageSize( pageSize ); params.setTotalPages( totalPages ); params.setSkipPaging( skipPaging ); params.setIncludeAttributes( includeAttributes ); params.setOrders( orders ); params.setEvents( events ); return params; } @Override public Event getEvent( String uid ) { ProgramStageInstance psi = programStageInstanceService.getProgramStageInstance( uid ); return psi != null ? convertProgramStageInstance( psi ) : null; } @Override public Event getEvent( ProgramStageInstance programStageInstance ) { return convertProgramStageInstance( programStageInstance ); } // ------------------------------------------------------------------------- // UPDATE // ------------------------------------------------------------------------- @Override public ImportSummaries updateEvents( List<Event> events, boolean singleValue ) { ImportSummaries importSummaries = new ImportSummaries(); int counter = 0; User user = currentUserService.getCurrentUser(); for ( Event event : events ) { importSummaries.addImportSummary( updateEvent( event, user, singleValue, null ) ); if ( counter % FLUSH_FREQUENCY == 0 ) { dbmsManager.clearSession(); } counter++; } return importSummaries; } @Override public ImportSummary updateEvent( Event event, boolean singleValue ) { return updateEvent( event, singleValue, null ); } @Override public ImportSummary updateEvent( Event event, boolean singleValue, ImportOptions importOptions ) { return updateEvent( event, currentUserService.getCurrentUser(), singleValue, importOptions ); } private ImportSummary updateEvent( Event event, User user, boolean singleValue, ImportOptions importOptions ) { if ( importOptions == null ) { importOptions = new ImportOptions(); } ImportSummary importSummary = new ImportSummary(); ProgramStageInstance programStageInstance = programStageInstanceService .getProgramStageInstance( event.getEvent() ); if ( programStageInstance == null ) { importSummary.getConflicts().add( new ImportConflict( "Invalid Event ID.", event.getEvent() ) ); return importSummary.incrementIgnored(); } OrganisationUnit organisationUnit = getOrganisationUnit( importOptions.getIdSchemes(), event.getOrgUnit() ); if ( organisationUnit == null ) { organisationUnit = programStageInstance.getOrganisationUnit(); } Date executionDate = new Date(); if ( event.getEventDate() != null ) { executionDate = DateUtils.parseDate( event.getEventDate() ); programStageInstance.setExecutionDate( executionDate ); } Date dueDate = new Date(); if ( event.getDueDate() != null ) { dueDate = DateUtils.parseDate( event.getDueDate() ); } String storedBy = getStoredBy( event, null, user ); programStageInstance.setStoredBy( storedBy ); String completedBy = getCompletedBy( event, null, user ); if ( event.getStatus() == EventStatus.ACTIVE ) { programStageInstance.setStatus( EventStatus.ACTIVE ); programStageInstance.setCompletedBy( null ); programStageInstance.setCompletedDate( null ); } else if ( programStageInstance.getStatus() != event.getStatus() && event.getStatus() == EventStatus.COMPLETED ) { programStageInstance.setStatus( EventStatus.COMPLETED ); programStageInstance.setCompletedBy( completedBy ); programStageInstance.setCompletedDate( executionDate ); if ( programStageInstance.isCompleted() ) { programStageInstanceService.completeProgramStageInstance( programStageInstance, importOptions.isSkipNotifications(), i18nManager.getI18nFormat() ); } } else if ( event.getStatus() == EventStatus.SKIPPED ) { programStageInstance.setStatus( EventStatus.SKIPPED ); } else if ( event.getStatus() == EventStatus.SCHEDULE ) { programStageInstance.setStatus( EventStatus.SCHEDULE ); } programStageInstance.setDueDate( dueDate ); programStageInstance.setOrganisationUnit( organisationUnit ); if ( !singleValue ) { if ( programStageInstance.getProgramStage().getCaptureCoordinates() && event.getCoordinate().isValid() ) { programStageInstance.setLatitude( event.getCoordinate().getLatitude() ); programStageInstance.setLongitude( event.getCoordinate().getLongitude() ); } else { programStageInstance.setLatitude( null ); programStageInstance.setLongitude( null ); } } Program program = getProgram( importOptions.getIdSchemes().getProgramIdScheme(), event.getProgram() ); validateExpiryDays( event, program, programStageInstance ); programStageInstanceService.updateProgramStageInstance( programStageInstance ); saveTrackedEntityComment( programStageInstance, event, storedBy ); Set<TrackedEntityDataValue> dataValues = new HashSet<>( dataValueService.getTrackedEntityDataValues( programStageInstance ) ); Map<String, TrackedEntityDataValue> existingDataValues = getDataElementDataValueMap( dataValues ); for ( DataValue value : event.getDataValues() ) { DataElement dataElement = getDataElement( importOptions.getIdSchemes().getDataElementIdScheme(), value.getDataElement() ); TrackedEntityDataValue dataValue = dataValueService.getTrackedEntityDataValue( programStageInstance, dataElement ); if ( !validateDataValue( dataElement, value.getValue(), importSummary ) ) { continue; } if ( dataValue != null ) { if ( StringUtils.isEmpty( value.getValue() ) && dataElement.isFileType() && !StringUtils.isEmpty( dataValue.getValue() ) ) { fileResourceService.deleteFileResource( dataValue.getValue() ); } dataValue.setValue( value.getValue() ); dataValue.setProvidedElsewhere( value.getProvidedElsewhere() ); dataValueService.updateTrackedEntityDataValue( dataValue ); dataValues.remove( dataValue ); } else { TrackedEntityDataValue existingDataValue = existingDataValues.get( value.getDataElement() ); saveDataValue( programStageInstance, event.getStoredBy(), dataElement, value.getValue(), value.getProvidedElsewhere(), existingDataValue, null ); } } if ( !singleValue ) { dataValues.forEach( dataValueService::deleteTrackedEntityDataValue ); } return importSummary; } @Override public void updateEventForNote( Event event ) { ProgramStageInstance programStageInstance = programStageInstanceService .getProgramStageInstance( event.getEvent() ); if ( programStageInstance == null ) { return; } saveTrackedEntityComment( programStageInstance, event, getStoredBy( event, null, currentUserService.getCurrentUser() ) ); } @Override public void updateEventForEventDate( Event event ) { ProgramStageInstance programStageInstance = programStageInstanceService .getProgramStageInstance( event.getEvent() ); if ( programStageInstance == null ) { return; } Date executionDate = new Date(); if ( event.getEventDate() != null ) { executionDate = DateUtils.parseDate( event.getEventDate() ); } if ( event.getStatus() == EventStatus.COMPLETED ) { programStageInstance.setStatus( EventStatus.COMPLETED ); } else { programStageInstance.setStatus( EventStatus.VISITED ); } ImportOptions importOptions = new ImportOptions(); OrganisationUnit organisationUnit = getOrganisationUnit( importOptions.getIdSchemes(), event.getOrgUnit() ); if ( organisationUnit == null ) { organisationUnit = programStageInstance.getOrganisationUnit(); } programStageInstance.setOrganisationUnit( organisationUnit ); programStageInstance.setExecutionDate( executionDate ); programStageInstanceService.updateProgramStageInstance( programStageInstance ); } // ------------------------------------------------------------------------- // DELETE // ------------------------------------------------------------------------- @Override public ImportSummary deleteEvent( String uid ) { ProgramStageInstance programStageInstance = programStageInstanceService.getProgramStageInstance( uid ); if ( programStageInstance != null ) { programStageInstanceService.deleteProgramStageInstance( programStageInstance ); return new ImportSummary( ImportStatus.SUCCESS, "Deletion of event " + uid + " was successful" ) .incrementDeleted(); } return new ImportSummary( ImportStatus.ERROR, "ID " + uid + " does not point to a valid event: " + uid ) .incrementIgnored(); } @Override public ImportSummaries deleteEvents( List<String> uids ) { ImportSummaries importSummaries = new ImportSummaries(); int counter = 0; for ( String uid : uids ) { importSummaries.addImportSummary( deleteEvent( uid ) ); if ( counter % FLUSH_FREQUENCY == 0 ) { dbmsManager.clearSession(); } counter++; } return importSummaries; } // ------------------------------------------------------------------------- // HELPERS // ------------------------------------------------------------------------- private Event convertProgramStageInstance( ProgramStageInstance programStageInstance ) { if ( programStageInstance == null ) { return null; } Event event = new Event(); event.setEvent( programStageInstance.getUid() ); if ( programStageInstance.getProgramInstance().getEntityInstance() != null ) { event.setTrackedEntityInstance( programStageInstance.getProgramInstance().getEntityInstance().getUid() ); } event.setFollowup( programStageInstance.getProgramInstance().getFollowup() ); event.setEnrollmentStatus( EnrollmentStatus.fromProgramStatus( programStageInstance.getProgramInstance().getStatus() ) ); event.setStatus( programStageInstance.getStatus() ); event.setEventDate( DateUtils.getIso8601NoTz( programStageInstance.getExecutionDate() ) ); event.setDueDate( DateUtils.getIso8601NoTz( programStageInstance.getDueDate() ) ); event.setStoredBy( programStageInstance.getStoredBy() ); event.setCompletedBy( programStageInstance.getCompletedBy() ); event.setCompletedDate( DateUtils.getIso8601NoTz( programStageInstance.getCompletedDate() ) ); event.setCreated( DateUtils.getIso8601NoTz( programStageInstance.getCreated() ) ); event.setLastUpdated( DateUtils.getIso8601NoTz( programStageInstance.getLastUpdated() ) ); UserCredentials userCredentials = currentUserService.getCurrentUser().getUserCredentials(); OrganisationUnit ou = programStageInstance.getOrganisationUnit(); if ( ou != null ) { if ( !organisationUnitService.isInUserHierarchy( ou ) ) { if ( !userCredentials.isSuper() && !userCredentials.isAuthorized( "F_TRACKED_ENTITY_INSTANCE_SEARCH_IN_ALL_ORGUNITS" ) ) { throw new IllegalQueryException( "User has no access to organisation unit: " + ou.getUid() ); } } event.setOrgUnit( ou.getUid() ); } Program program = programStageInstance.getProgramInstance().getProgram(); if ( !userCredentials.isSuper() && !userCredentials.getAllPrograms().contains( program ) ) { throw new IllegalQueryException( "User has no access to program: " + program.getUid() ); } event.setProgram( program.getUid() ); event.setEnrollment( programStageInstance.getProgramInstance().getUid() ); event.setProgramStage( programStageInstance.getProgramStage().getUid() ); if ( programStageInstance.getProgramInstance().getEntityInstance() != null ) { event.setTrackedEntityInstance( programStageInstance.getProgramInstance().getEntityInstance().getUid() ); } if ( programStageInstance.getProgramStage().getCaptureCoordinates() ) { Coordinate coordinate = null; if ( programStageInstance.getLongitude() != null && programStageInstance.getLatitude() != null ) { coordinate = new Coordinate( programStageInstance.getLongitude(), programStageInstance.getLatitude() ); try { List<Double> list = OBJECT_MAPPER.readValue( coordinate.getCoordinateString(), new TypeReference<List<Double>>() { } ); coordinate.setLongitude( list.get( 0 ) ); coordinate.setLatitude( list.get( 1 ) ); } catch ( IOException ignored ) { } } if ( coordinate != null && coordinate.isValid() ) { event.setCoordinate( coordinate ); } } Collection<TrackedEntityDataValue> dataValues = dataValueService .getTrackedEntityDataValues( programStageInstance ); for ( TrackedEntityDataValue dataValue : dataValues ) { DataValue value = new DataValue(); value.setCreated( DateUtils.getIso8601NoTz( dataValue.getCreated() ) ); value.setLastUpdated( DateUtils.getIso8601NoTz( dataValue.getLastUpdated() ) ); value.setDataElement( dataValue.getDataElement().getUid() ); value.setValue( dataValue.getValue() ); value.setProvidedElsewhere( dataValue.getProvidedElsewhere() ); value.setStoredBy( dataValue.getStoredBy() ); event.getDataValues().add( value ); } List<TrackedEntityComment> comments = programStageInstance.getComments(); for ( TrackedEntityComment comment : comments ) { Note note = new Note(); note.setValue( comment.getCommentText() ); note.setStoredBy( comment.getCreator() ); if ( comment.getCreatedDate() != null ) { note.setStoredDate( DateUtils.getIso8601NoTz( comment.getCreatedDate() ) ); } event.getNotes().add( note ); } return event; } private boolean canAccess( Program program, User user ) { if ( accessibleProgramsCache.isEmpty() ) { accessibleProgramsCache = programService.getUserPrograms( user ); } return accessibleProgramsCache.contains( program ); } private boolean validateDataValue( DataElement dataElement, String value, ImportSummary importSummary ) { String status = ValidationUtils.dataValueIsValid( value, dataElement ); if ( status != null ) { importSummary.getConflicts().add( new ImportConflict( dataElement.getUid(), status ) ); importSummary.getImportCount().incrementIgnored(); return false; } return true; } private ImportSummary saveEvent( Program program, ProgramInstance programInstance, ProgramStage programStage, ProgramStageInstance programStageInstance, OrganisationUnit organisationUnit, Event event, User user, ImportOptions importOptions ) { Assert.notNull( program ); Assert.notNull( programInstance ); Assert.notNull( programStage ); ImportSummary importSummary = new ImportSummary(); importSummary.setStatus( ImportStatus.SUCCESS ); if ( importOptions == null ) { importOptions = new ImportOptions(); } boolean existingEvent = programStageInstance != null; boolean dryRun = importOptions.isDryRun(); Date executionDate = null; // = new Date(); if ( event.getEventDate() != null ) { executionDate = DateUtils.parseDate( event.getEventDate() ); } Date dueDate = new Date(); if ( event.getDueDate() != null ) { dueDate = DateUtils.parseDate( event.getDueDate() ); } String storedBy = getStoredBy( event, importSummary, user ); String completedBy = getCompletedBy( event, importSummary, user ); DataElementCategoryOptionCombo coc = null; if ( event.getAttributeCategoryOptions() != null && program.getCategoryCombo() != null ) { IdScheme idScheme = importOptions.getIdSchemes().getCategoryOptionIdScheme(); try { coc = inputUtils.getAttributeOptionCombo( program.getCategoryCombo(), event.getAttributeCategoryOptions(), idScheme ); } catch ( IllegalQueryException ex ) { importSummary.getConflicts() .add( new ImportConflict( ex.getMessage(), event.getAttributeCategoryOptions() ) ); } } else { coc = categoryService.getDefaultDataElementCategoryOptionCombo(); } if ( !dryRun ) { if ( programStageInstance == null ) { programStageInstance = createProgramStageInstance( programStage, programInstance, organisationUnit, dueDate, executionDate, event.getStatus().getValue(), event.getCoordinate(), completedBy, event.getEvent(), coc, importOptions ); } else { updateProgramStageInstance( programStage, programInstance, organisationUnit, dueDate, executionDate, event.getStatus().getValue(), event.getCoordinate(), completedBy, programStageInstance, coc, importOptions ); } saveTrackedEntityComment( programStageInstance, event, storedBy ); importSummary.setReference( programStageInstance.getUid() ); } Map<String, TrackedEntityDataValue> dataElementValueMap = Maps.newHashMap(); if ( existingEvent ) { dataElementValueMap = getDataElementDataValueMap( dataValueService.getTrackedEntityDataValues( programStageInstance ) ); } for ( DataValue dataValue : event.getDataValues() ) { DataElement dataElement; if ( dataElementValueMap.containsKey( dataValue.getDataElement() ) ) { dataElement = dataElementValueMap.get( dataValue.getDataElement() ).getDataElement(); } else { dataElement = getDataElement( importOptions.getIdSchemes().getDataElementIdScheme(), dataValue.getDataElement() ); } if ( dataElement != null ) { if ( validateDataValue( dataElement, dataValue.getValue(), importSummary ) ) { String dataValueStoredBy = dataValue.getStoredBy() != null ? dataValue.getStoredBy() : storedBy; if ( !dryRun ) { TrackedEntityDataValue existingDataValue = dataElementValueMap .get( dataValue.getDataElement() ); saveDataValue( programStageInstance, dataValueStoredBy, dataElement, dataValue.getValue(), dataValue.getProvidedElsewhere(), existingDataValue, importSummary ); } } } else { importSummary.getConflicts().add( new ImportConflict( "dataElement", dataValue.getDataElement() + " is not a valid data element" ) ); importSummary.getImportCount().incrementIgnored(); } } return importSummary; } private void saveDataValue( ProgramStageInstance programStageInstance, String storedBy, DataElement dataElement, String value, Boolean providedElsewhere, TrackedEntityDataValue dataValue, ImportSummary importSummary ) { if ( value != null && value.trim().length() == 0 ) { value = null; } if ( value != null ) { if ( dataValue == null ) { dataValue = new TrackedEntityDataValue( programStageInstance, dataElement, value ); dataValue.setStoredBy( storedBy ); dataValue.setProvidedElsewhere( providedElsewhere ); dataValueService.saveTrackedEntityDataValue( dataValue ); if ( importSummary != null ) { importSummary.getImportCount().incrementImported(); } } else { dataValue.setValue( value ); dataValue.setStoredBy( storedBy ); dataValue.setProvidedElsewhere( providedElsewhere ); dataValueService.updateTrackedEntityDataValue( dataValue ); if ( importSummary != null ) { importSummary.getImportCount().incrementUpdated(); } } } else if ( dataValue != null ) { dataValueService.deleteTrackedEntityDataValue( dataValue ); if ( importSummary != null ) { importSummary.getImportCount().incrementDeleted(); } } } private ProgramStageInstance createProgramStageInstance( ProgramStage programStage, ProgramInstance programInstance, OrganisationUnit organisationUnit, Date dueDate, Date executionDate, int status, Coordinate coordinate, String completedBy, String programStageInstanceUid, DataElementCategoryOptionCombo coc, ImportOptions importOptions ) { ProgramStageInstance programStageInstance = new ProgramStageInstance(); programStageInstance.setUid( CodeGenerator.isValidCode( programStageInstanceUid ) ? programStageInstanceUid : CodeGenerator.generateCode() ); updateProgramStageInstance( programStage, programInstance, organisationUnit, dueDate, executionDate, status, coordinate, completedBy, programStageInstance, coc, importOptions ); return programStageInstance; } private void updateProgramStageInstance( ProgramStage programStage, ProgramInstance programInstance, OrganisationUnit organisationUnit, Date dueDate, Date executionDate, int status, Coordinate coordinate, String completedBy, ProgramStageInstance programStageInstance, DataElementCategoryOptionCombo coc, ImportOptions importOptions ) { programStageInstance.setProgramInstance( programInstance ); programStageInstance.setProgramStage( programStage ); programStageInstance.setDueDate( dueDate ); programStageInstance.setExecutionDate( executionDate ); programStageInstance.setOrganisationUnit( organisationUnit ); programStageInstance.setAttributeOptionCombo( coc ); if ( programStage.getCaptureCoordinates() ) { if ( coordinate != null && coordinate.isValid() ) { programStageInstance.setLongitude( coordinate.getLongitude() ); programStageInstance.setLatitude( coordinate.getLatitude() ); } } programStageInstance.setStatus( EventStatus.fromInt( status ) ); if ( programStageInstance.getId() == 0 ) { programStageInstance.setAutoFields(); sessionFactory.getCurrentSession().save( programStageInstance ); } else { sessionFactory.getCurrentSession().update( programStageInstance ); sessionFactory.getCurrentSession().refresh( programStageInstance ); } if ( programStageInstance.isCompleted() ) { programStageInstance.setStatus( EventStatus.COMPLETED ); programStageInstance.setCompletedDate( new Date() ); programStageInstance.setCompletedBy( completedBy ); programStageInstanceService.completeProgramStageInstance( programStageInstance, importOptions.isSkipNotifications(), i18nManager.getI18nFormat() ); } } private void saveTrackedEntityComment( ProgramStageInstance programStageInstance, Event event, String storedBy ) { for ( Note note : event.getNotes() ) { TrackedEntityComment comment = new TrackedEntityComment(); comment.setCreator( storedBy ); comment.setCreatedDate( new Date() ); comment.setCommentText( note.getValue() ); commentService.addTrackedEntityComment( comment ); programStageInstance.getComments().add( comment ); programStageInstanceService.updateProgramStageInstance( programStageInstance ); } } private String getCompletedBy( Event event, ImportSummary importSummary, User fallbackUser ) { String completedBy = event.getCompletedBy(); if ( completedBy == null ) { completedBy = User.getSafeUsername( fallbackUser ); } else if ( completedBy.length() >= 31 ) { if ( importSummary != null ) { importSummary.getConflicts().add( new ImportConflict( "completed by", completedBy + " is more than 31 characters, using current username instead" ) ); } completedBy = User.getSafeUsername( fallbackUser ); } return completedBy; } private String getStoredBy( Event event, ImportSummary importSummary, User fallbackUser ) { String storedBy = event.getStoredBy(); if ( storedBy == null ) { storedBy = User.getSafeUsername( fallbackUser ); } else if ( storedBy.length() >= 31 ) { if ( importSummary != null ) { importSummary.getConflicts().add( new ImportConflict( "stored by", storedBy + " is more than 31 characters, using current username instead" ) ); } storedBy = User.getSafeUsername( fallbackUser ); } return storedBy; } private Map<String, TrackedEntityDataValue> getDataElementDataValueMap( Collection<TrackedEntityDataValue> dataValues ) { return dataValues.stream().collect( Collectors.toMap( dv -> dv.getDataElement().getUid(), dv -> dv ) ); } private OrganisationUnit getOrganisationUnit( IdSchemes idSchemes, String id ) { return organisationUnitCache.get( id, new IdentifiableObjectCallable<>( manager, OrganisationUnit.class, idSchemes.getOrgUnitIdScheme(), id ) ); } private Program getProgram( IdScheme idScheme, String id ) { return programCache.get( id, new IdentifiableObjectCallable<>( manager, Program.class, idScheme, id ) ); } private ProgramStage getProgramStage( IdScheme idScheme, String id ) { return programStageCache.get( id, new IdentifiableObjectCallable<>( manager, ProgramStage.class, idScheme, id ) ); } private DataElement getDataElement( IdScheme idScheme, String id ) { return dataElementCache.get( id, new IdentifiableObjectCallable<>( manager, DataElement.class, idScheme, id ) ); } @Override public void validate( EventSearchParams params ) throws IllegalQueryException { String violation = null; if ( params == null ) { throw new IllegalQueryException( "Query parameters can not be empty." ); } if ( params.getProgram() == null && params.getOrgUnit() == null && params.getTrackedEntityInstance() == null && params.getEvents().isEmpty() ) { violation = "At least one of the following query parameters are required: orgUnit, program, trackedEntityInstance or event."; } if ( violation != null ) { log.warn( "Validation failed: " + violation ); throw new IllegalQueryException( violation ); } } private void validateExpiryDays( Event event, Program program, ProgramStageInstance programStageInstance ) { if ( program != null ) { if ( program.getCompleteEventsExpiryDays() > 0 ) { if ( event.getStatus() == EventStatus.COMPLETED || programStageInstance != null && programStageInstance.getStatus() == EventStatus.COMPLETED ) { Date referenceDate = null; if ( programStageInstance != null ) { referenceDate = programStageInstance.getCompletedDate(); } else { if ( event.getCompletedDate() != null ) { referenceDate = DateUtils.parseDate( event.getCompletedDate() ); } } if ( referenceDate == null ) { throw new IllegalQueryException( "Event needs to have completed date." ); } if ( (new Date()).after( DateUtils.getDateAfterAddition( referenceDate, program.getCompleteEventsExpiryDays() ) ) ) { throw new IllegalQueryException( "The event's completness date has expired. Not possible to make changes to this event" ); } } } PeriodType periodType = program.getExpiryPeriodType(); if ( periodType != null && program.getExpiryDays() > 0 ) { if ( programStageInstance != null ) { Date today = new Date(); if ( programStageInstance.getExecutionDate() == null ) { throw new IllegalQueryException( "Event needs to have event date." ); } Period period = periodType.createPeriod( programStageInstance.getExecutionDate() ); if ( today.after( DateUtils.getDateAfterAddition( period.getEndDate(), program.getExpiryDays() ) ) ) { throw new IllegalQueryException( "The program's expiry date has passed. It is not possible to make changes to this event." ); } } else { String referenceDate = event.getEventDate() != null ? event.getEventDate() : event.getDueDate() != null ? event.getDueDate() : null; if ( referenceDate == null ) { throw new IllegalQueryException( "Event needs to have at least one (event or schedule) date. " ); } Period period = periodType.createPeriod( new Date() ); if ( DateUtils.parseDate( referenceDate ).before( period.getStartDate() ) ) { throw new IllegalQueryException( "The event's date belongs to an expired period. It is not possble to create such event." ); } } } } } }
update coordinates for updateEvent
dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/events/event/AbstractEventService.java
update coordinates for updateEvent
Java
mit
72b615f5761213b5de526450c17bef59c2bce4fe
0
sagevoice/JavaCola
package edu.monash.infotech.marvl.cola; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.MapType; import edu.monash.infotech.marvl.cola.powergraph.Configuration; import edu.monash.infotech.marvl.cola.powergraph.LinkTypeAccessor; import edu.monash.infotech.marvl.cola.powergraph.Module; import edu.monash.infotech.marvl.cola.powergraph.PowerEdge; import edu.monash.infotech.marvl.cola.shortestpaths.Calculator; import edu.monash.infotech.marvl.cola.vpsc.*; import lombok.extern.slf4j.Slf4j; import org.testng.Assert; import org.testng.annotations.*; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.ToDoubleFunction; import java.util.function.ToIntFunction; import java.util.stream.Collectors; @Slf4j public class Tests { private double nodeDistance(final GraphNode u, final GraphNode v) { final double dx = u.x - v.x, dy = u.y - v.y; return Math.sqrt(dx * dx + dy * dy); } private boolean approxEquals(final double actual, final double expected, final double threshold) { return Math.abs(actual - expected) <= threshold; } private List<Link> mapJsonArrayToLinkList(final List<Map<String, Object>> jsonArray) { final List<Link> result = jsonArray.stream().map(jsonObj -> { return new Link(jsonObj.get("source"), jsonObj.get("target")); }).collect(Collectors.toList()); return result; } private List<GraphNode> mapJsonArrayToNodeList(final List<Map<String, Object>> jsonArray) { final List<GraphNode> result = jsonArray.stream().map(jsonObj -> { return new GraphNode(); }).collect(Collectors.toList()); return result; } @Test(description="small power-graph") public void smallPowerGraphTest () { try (final InputStream stream = getClass().getResourceAsStream("/n7e23.json")) { final ObjectMapper mapper = new ObjectMapper(); final MapType type = mapper.getTypeFactory().constructMapType( Map.class, String.class, Object.class); final Map<String, Object> graph = mapper.readValue(stream, type); final int n = ((List)graph.get("nodes")).size(); Assert.assertEquals(n, 7); List<Link> links = mapJsonArrayToLinkList((List<Map<String, Object>>)graph.get("links")); LinkTypeAccessor<Link> linkAccessor = new IntegerLinkAccessor(); Configuration<Link> c = new Configuration<>(n, links, linkAccessor); Assert.assertEquals(c.modules.size(), 7); List<PowerEdge> es = c.allEdges(); Assert.assertEquals(c.R, es.size(), "c.R=" + c.R + ", actual edges in c=" + es.size()); Module m = c.merge(c.modules.get(0), c.modules.get(4)); Assert.assertTrue(m.children.contains(0)); Assert.assertTrue(m.children.contains(4)); Assert.assertTrue(m.outgoing.contains(1)); Assert.assertTrue(m.outgoing.contains(3)); Assert.assertTrue(m.outgoing.contains(5)); Assert.assertTrue(m.outgoing.contains(6)); Assert.assertTrue(m.incoming.contains(2)); Assert.assertTrue(m.incoming.contains(5)); es = c.allEdges(); Assert.assertEquals(c.R, es.size(), "c.R=" + c.R + ", actual edges in c=" + es.size()); m = c.merge(c.modules.get(2), c.modules.get(3)); es = c.allEdges(); Assert.assertEquals(c.R, es.size(), "c.R=" + c.R + ", actual edges in c=" + es.size()); c = new Configuration<>(n, links, linkAccessor); int lastR = c.R; while (c.greedyMerge()) { Assert.assertTrue(c.R < lastR); lastR = c.R; } List<PowerEdge> finalEdges = new ArrayList<>(); List<PowerEdge> powerEdges = c.allEdges(); Assert.assertEquals(powerEdges.size(), 7); List<Group> groups = c.getGroupHierarchy(finalEdges); Assert.assertEquals(groups.size(), 4); } catch (IOException e) { log.error("IOException in smallPowerGraphTest", e); throw new RuntimeException(e); } Assert.assertTrue(true); } @Test(description="all-pairs shortest paths") public void allPairsShortestPathsTest() { LayoutAdaptor d3cola = CoLa.adaptor(); try (final InputStream stream = getClass().getResourceAsStream("/triangle.json")) { final ObjectMapper mapper = new ObjectMapper(); final MapType type = mapper.getTypeFactory().constructMapType( Map.class, String.class, Object.class); final Map<String, Object> graph = mapper.readValue(stream, type); List<Link> links = mapJsonArrayToLinkList((List<Map<String, Object>>)graph.get("links")); List<GraphNode> nodes = mapJsonArrayToNodeList((List<Map<String, Object>>)graph.get("nodes")); d3cola .nodes(nodes) .links(links) .linkDistance(Double.valueOf(1)); final int n = d3cola.nodes().size(); Assert.assertEquals(n, 4); final ToIntFunction<Link> getSourceIndex = (e) -> { return ((Integer)e.source).intValue(); }; final ToIntFunction<Link> getTargetIndex = (e) -> { return ((Integer)e.target).intValue(); }; ToDoubleFunction<Link> getLength = (e) -> { return 1; }; double[][] D = (new Calculator<>(n, d3cola.links(), getSourceIndex, getTargetIndex, getLength)).DistanceMatrix(); Assert.assertEquals(D, new double[][]{ {0, 1, 1, 2}, {1, 0, 1, 2}, {1, 1, 0, 1}, {2, 2, 1, 0}, }); double[] x = new double[]{0, 0, 1, 1}, y = new double[]{1, 0, 0, 1}; Descent descent = new Descent(new double[][]{x, y}, D); double s0 = descent.reduceStress(); double s1 = descent.reduceStress(); Assert.assertTrue(s1 < s0); double s2 = descent.reduceStress(); Assert.assertTrue(s2 < s1); d3cola.start(0,0,10); final List<Double> lengths = d3cola.links().stream().map(l -> { GraphNode u = (GraphNode)l.source, v = (GraphNode)l.target; double dx = u.x - v.x, dy = u.y - v.y; return Math.sqrt(dx*dx + dy*dy); }).collect(Collectors.toList()); Function<List<Double>, Double> avg = (a) -> { return a.stream().reduce( new Double(0), (u, v) -> { return u + v; }) / a.size(); }; final double mean = avg.apply(lengths); final double variance = avg.apply(lengths.stream().map( (l) -> { double d = mean - l; return d * d; }).collect(Collectors.toList())); Assert.assertTrue(variance < 0.1); } catch (IOException e) { log.error("IOException in allPairsShortestPathsTest", e); throw new RuntimeException(e); } Assert.assertTrue(true); } @Test(description="edge lengths") public void edgeLengthsTest () { LayoutAdaptor d3cola = CoLa.adaptor(); try (final InputStream stream = getClass().getResourceAsStream("/triangle.json")) { final ObjectMapper mapper = new ObjectMapper(); final MapType type = mapper.getTypeFactory().constructMapType( Map.class, String.class, Object.class); final Map<String, Object> graph = mapper.readValue(stream, type); List<Link> links = mapJsonArrayToLinkList((List<Map<String, Object>>)graph.get("links")); List<GraphNode> nodes = mapJsonArrayToNodeList((List<Map<String, Object>>)graph.get("nodes")); final ToDoubleFunction<Link> length = (l) -> { return Layout.linkId(l) == "2-3" ? 2 : 1; }; d3cola .linkDistance(length) .nodes(nodes) .links(links); d3cola.start(100); List<Double> errors = d3cola.links().stream().map((e) -> { double l = nodeDistance((GraphNode)e.source, (GraphNode)e.target); return Math.abs(l - length.applyAsDouble(e)); }).collect(Collectors.toList()); Function<List<Double>, Double> listMax = (a) -> { return a.stream().reduce( new Double(0), (u, v) -> { return Math.max(u, v); }); }; double max = listMax.apply(errors); Assert.assertTrue(max < 0.1, "max = " + max); } catch (IOException e) { log.error("IOException in edgeLengthsTest", e); throw new RuntimeException(e); } Assert.assertTrue(true); } /* @Test(description="group") public void groupTest () { LayoutAdaptor d3cola = CoLa.adaptor(); var length = (l) -> { return d3cola.linkId(l) == "2-3" ? 2 : 1; } var nodes = []; var u = { x: -5, y: 0, width: 10, height: 10 }; var v = { x: 5, y: 0, width: 10, height: 10 }; var g = { padding: 10, leaves: [0] }; d3cola .linkDistance(length) .avoidOverlaps(true) .nodes([u,v]) .groups([g]); d3cola.start(10, 10, 10); Assert.assertTrue(approxEquals(g.bounds.width(), 30, 0.1)); Assert.assertTrue(approxEquals(g.bounds.height(), 30, 0.1)); Assert.assertTrue(approxEquals(Math.abs(u.y - v.y), 20, 0.1)); } @Test(description="equality constraints") public void equalityConstraintsTest() { LayoutAdaptor d3cola = CoLa.adaptor(); d3.json("../examples/graphdata/triangle.json", function (error, graph) { d3cola .nodes(graph.nodes) .links(graph.links) .constraints([{ type: "separation", axis: "x", left: 0, right: 1, gap: 0, equality: true }, { type: "separation", axis: "y", left: 0, right: 2, gap: 0, equality: true }]); d3cola.start(20, 20, 20); Assert.assertTrue(Math.abs(graph.nodes[0].x - graph.nodes[1].x) < 0.001); Assert.assertTrue(Math.abs(graph.nodes[0].y - graph.nodes[2].y) < 0.001); start(); }); Assert.assertTrue(true); } private int nextInt(final PseudoRandom rand, final int r) { return (int)Math.round(rand.getNext() * r); } @Test(description="convex hulls") public void convexHullsTest() { PseudoRandom rand = new PseudoRandom(); var width = 100, height = 100; for (var k = 0; k < 10; ++k) { var P = []; for (var i = 0; i < 5; ++i) { var p; P.push(p = { x: nextInt(width), y: nextInt(height) }); } var h = Geom.ConvexHull(P); for (var i = 2; i < h.length; ++i) { var p = h[i - 2], q = h[i - 1], r = h[i]; Assert.assertTrue(Geom.isLeft(p, q, r) >= 0, "clockwise hull " + i); for (var j = 0; j < P.length; ++j) { Assert.assertTrue(Geom.isLeft(p, q, P[j]) >= 0, "" + j); } } Assert.assertTrue(h[0] != = h[h.length - 1], "first and last point of hull are different" + k); } } @Test(description="radial sort") public void radialSortTest() { var n = 100; var width = 400, height = 400; var P = []; var x = 0, y = 0; PseudoRandom rand = new PseudoRandom(5); for (var i = 0; i < n; ++i) { var p; P.push(p = { x: nextInt(width), y: nextInt(height) }); x += p.x; y += p.y; } var q = { x: x / n, y: y / n }; //console.log(q); var p0 = null; Geom.clockwiseRadialSweep(q, P, (p, i) -> { if (p0) { var il = Geom.isLeft(q, p0, p); Assert.assertTrue(il >= 0); } p0 = p; }); } private double length(final Point p, final Point q) { final double dx = p.x - q.x, dy = p.y - q.y; return dx * dx + dy * dy; } private Point[] makePoly(final PseudoRandom rand) { return makePoly(rand, 10, 10); } private Point[] makePoly(final PseudoRandom rand, final double width, final double height) { var n = nextInt(rand, 7) + 3; var P = []; loop: for (var i = 0; i < n; ++i) { var p = { x: nextInt(width), y: nextInt(height) }; var ctr = 0; while (i > 0 && length(P[i - 1], p) < 1 // min segment length is 1 || i > 1 && ( // new point must keep poly convex Geom.isLeft(P[i - 2], P[i - 1], p) <= 0 || Geom.isLeft(P[i - 1], p, P[0]) <= 0 || Geom.isLeft(p, P[0], P[1]) <= 0)) { if (ctr++ > 10) break loop; // give up after ten tries (maybe not enough space left for another convex point) p = { x: nextInt(width), y: nextInt(height) }; } P.push(p); } if (P.length > 2) { // must be at least triangular P.push({ x: P[0].x, y: P[0].y }); return P; } return makePoly(rand, width, height); } private List<Point[]> makeNonoverlappingPolys(final PseudoRandom rand, final int n) { var P = []; var overlaps = function (p) { for (var i = 0; i < P.length; i++) { var q = P[i]; if (Geom.polysOverlap(p, q)) return true; } return false; } for (var i = 0; i < n; i++) { var p = makePoly(rand); while (overlaps(p)) { var dx = nextInt(10) - 5, dy = nextInt(10) - 5; p.forEach(function (p) { p.x += dx; p.y += dy; }); } P.push(p); } var minX = 0, minY = 0; P.forEach(function (p) { p.forEach(function (p) { minX = Math.min(minX, p.x); minY = Math.min(minY, p.y); }) }); P.forEach(function (p) { p.forEach(function (p) { p.x -= minX; p.y -= minY; }); }); return P; } private Point midPoint(final Point p) { var mx = 0, my = 0; var n = p.length - 1; for (var i = 0; i < n; i++) { var q = p[i]; mx += q.x; my += q.y; } return { x: mx/n, y: my/n }; } private int countRouteIntersections(routes) { var ints = []; for (var i = 0; i < routes.length - 1; i++) { for (var j = i + 1; j < routes.length ; j++) { var r1 = routes[i], r2 = routes[j]; r1.forEach(function (s1) { r2.forEach(function (s2) { var int = Rectangle.lineIntersection(s1[0].x, s1[0].y, s1[1].x, s1[1].y, s2[0].x, s2[0].y, s2[1].x, s2[1].y); if (int) ints.push(int); }) }) } } return ints.length; } @Test(description="metro crossing min") public void metroCrossingMinTest () { var verts, edges, order, routes; function makeInstance() { verts.forEach(function (v, i) { v.id = i; v.edges = {}; }); edges.forEach(function (e, i) { e.id = i; }); } function twoParallelSegments() { verts = [ { x: 0, y: 10 }, { x: 10, y: 10 } ]; edges = [ [verts[0], verts[1]], [verts[0], verts[1]] ]; makeInstance(); } function threeByThreeSegments() { verts = [ { x: 0, y: 10 }, { x: 10, y: 10 }, { x: 10, y: 20 }, { x: 10, y: 30 }, { x: 20, y: 20 }, { x: 10, y: 0 }, { x: 0, y: 20 } ]; edges = [ [verts[0], verts[1], verts[2], verts[3]], [verts[0], verts[1], verts[2], verts[4]], [verts[5], verts[1], verts[2], verts[6]] ]; makeInstance(); } function regression1() { verts = [ {x:430.79999999999995, y:202.5}, {x:464.4, y:202.5}, {x:464.4, y:261.6666666666667}, {x:464.4, y:320.83333333333337}, {x:474, y:320.83333333333337}, {x:486, y:320.83333333333337}, {x:498.0000000000001, y:202.5}, {x:474, y:202.5}, ]; verts.forEach(function(v) { v.x -= 400; v.y -= 160; v.x /= 4; v.y /= 8; }); edges = [[ verts[0], verts[1], verts[2], verts[3], verts[4], verts[5] ], [ verts[6], verts[7], verts[1], verts[0] ]]; makeInstance(); } function nudge() { order = GridRouter.orderEdges(edges); routes = edges.map((e) -> { return GridRouter.makeSegments(e); }); GridRouter.nudgeSegments(routes, 'x', 'y', order, 2); GridRouter.nudgeSegments(routes, 'y', 'x', order, 2); GridRouter.unreverseEdges(routes, edges); } // trivial case twoParallelSegments(); nudge(); // two segments, one reversed edges[1].reverse(); nudge(); threeByThreeSegments(); var lcs = new ongestCommonSubsequence('ABAB'.split(''), 'DABA'.split('')); deepEqual(lcs.getSequence(), 'ABA'.split('')); lcs = new LongestCommonSubsequence(edges[0], edges[1]); Assert.assertEquals(lcs.length, 3); deepEqual(lcs.getSequence().map((v) -> { return v.id }), [0, 1, 2]); var e0reversed = edges[0].slice(0).reverse(); lcs = new LongestCommonSubsequence(e0reversed, edges[1]); deepEqual(lcs.getSequence().map((v) -> { return v.id }), [2, 1, 0]); Assert.assertTrue(lcs.reversed); nudge(); Assert.assertEquals(routes[0].length, 2); Assert.assertEquals(routes[1].length, 3); Assert.assertEquals(routes[2].length, 2); Assert.assertEquals(countRouteIntersections(routes), 2); // flip it in y and try again threeByThreeSegments(); verts.forEach( (v) -> { v.y = 30 - v.y }); nudge(); Assert.assertEquals(countRouteIntersections(routes), 2); // reverse the first edge path and see what happens threeByThreeSegments(); edges[0].reverse(); nudge(); Assert.assertEquals(countRouteIntersections(routes), 2); // reverse the second edge path threeByThreeSegments(); edges[1].reverse(); nudge(); Assert.assertEquals(countRouteIntersections(routes), 2); // reverse the first 2 edge paths threeByThreeSegments(); edges[0].reverse(); edges[1].reverse(); nudge(); Assert.assertEquals(countRouteIntersections(routes), 2); regression1(); nudge(); Assert.assertEquals(countRouteIntersections(routes), 0); } // next steps: // o label node and group centre and boundary vertices // - non-traversable regions (obstacles) are determined by finding the highest common ancestors of the source and target nodes // - to route each edge the weights of the edges are adjusted such that those inside obstacles // have infinite weight while those inside the source and target node have zero weight // - augment dijkstra with a cost for bends @Test(description="grid router") public void gridRouterTest() { d3.json("../examples/graphdata/tetrisbugmultiedgeslayout.json", function (error, graph) { var gridrouter = new GridRouter(graph.nodes,{ getChildren: function(v) { return v.children; }, getBounds: function(v) { return typeof v.bounds !== 'undefined' ? new Rectangle(v.bounds.x, v.bounds.X, v.bounds.y, v.bounds.Y) : undefined; } }); var source = 1, target = 2; var shortestPath = gridrouter.route(source, target); function check(expected) { Assert.assertTrue(gridrouter.obstacles.length == expected); Assert.assertTrue(gridrouter.obstacles.map((v) -> { return v.id }).indexOf(source) < 0); Assert.assertTrue(gridrouter.obstacles.map((v) -> { return v.id }).indexOf(target) < 0); } check(8); source = 0, target = 7; shortestPath = gridrouter.route(source, target); check(6); source = 4, target = 5; shortestPath = gridrouter.route(source, target); check(8); source = 11, target = 2; shortestPath = gridrouter.route(source, target); check(13); // group to node source = 16, target = 5; shortestPath = gridrouter.route(source, target); check(7); // bend minimal? source = 1, target = 2; shortestPath = gridrouter.route(source, target); start(); }); Assert.assertTrue(true); } @Test(description="shortest path with bends") public void shortestPathWithBendsTest() { // 0 - 1 - 2 // | | // 3 - 4 var nodes = [[0,0],[1,0],[2,0],[1,1],[2,1]]; var edges = [[0,1,1],[1,2,2],[1,3,1],[3,4,1],[2,4,2]]; function source(e) { return e[0]}; function target(e) { return e[1]}; function length(e) { return e[2]}; Calculator sp = new Calculator(nodes.length, edges, source, target, length); var path = sp.PathFromNodeToNodeWithPrevCost(0, 4, function (u,v,w){ var a = nodes[u], b = nodes[v], c = nodes[w]; var dx = Math.abs(c[0] - a[0]), dy = Math.abs(c[1] - a[1]); return dx > 0.01 && dy > 0.01 ? 1000 : 0; }); Assert.assertTrue(true); } @Test(description="tangent visibility graph") public void tangentVisibilityGraphTest() { for (var tt = 0; tt < 100; tt++) { PseudoRandom rand = new PseudoRandom(tt); nextInt = function (r) { return Math.round(rand.getNext() * r) }, n = 10, P = makeNonoverlappingPolys(rand, n), port1 = midPoint(P[8]), port2 = midPoint(P[9]); TangentVisibilityGraph g = new TangentVisibilityGraph(P); start = g.addPoint(port1, 8), end = g.addPoint(port2, 9); g.addEdgeIfVisible(port1, port2, 8, 9); var getSource = function (e) { return e.source.id }, getTarget = function(e) { return e.target.id}, getLength = function(e) { return e.length() } shortestPath = (new Calculator(g.V.length, g.E, getSource, getTarget, getLength)).PathFromNodeToNode(start.id, end.id); Assert.assertTrue(shortestPath.length > 0); } Assert.assertTrue(true); } @Test(description="tangents") public void tangentsTest() { PseudoRandom rand = new PseudoRandom(); var rect = [{ x: 10, y: 10 }, { x: 20, y: 10 }, { x: 10, y: 20 }, { x: 20, y: 20 }]; var pnt = [{ x: 0, y: 0 }]; var t1 = Geom.tangents(pnt, rect); for (var j = 0; j < 100; j++) { var A = makePoly(rand), B = makePoly(rand); B.forEach((p) -> { p.x += 11 }); //if (j !== 207) continue; var t = Geom.tangents(A, B); // ok(t.length === 4, t.length + " tangents found at j="+j); } Assert.assertTrue(true); } function intersects(l, P) { var ints = []; for (var i = 1; i < P.length; ++i) { var int = Rectangle.lineIntersection( l.x1, l.y1, l.x2, l.y2, P[i-1].x, P[i-1].y, P[i].x, P[i].y ); if (int) ints.push(int); } return ints; } @Test(description="pseudo random number test") public void pseudoRandomNumberTest() { PseudoRandom rand = new PseudoRandom(); for (var i = 0; i < 100; ++i) { var r = rand.getNext(); Assert.assertTrue(r <= 1, "r=" + r); Assert.assertTrue(r >= 0, "r=" + r); r = rand.getNextBetween(5, 10); Assert.assertTrue(r <= 10, "r=" + r); Assert.assertTrue(r >= 5, "r=" + r); r = rand.getNextBetween(-5, 0); Assert.assertTrue(r <= 0, "r=" + r); Assert.assertTrue(r >= -5, "r=" + r); //console.log(r); } } @Test(description="rectangle intersections") public void rectangleIntersectionsTest() { var r = new Rectangle(2, 4, 0, 2); var p = r.rayIntersection(0, 1); Assert.assertTrue(p.x == 2); Assert.assertTrue(p.y == 1); p = r.rayIntersection(0, 0); Assert.assertTrue(p.x == 2); } @Test(description="matrix perf test") public void matrixPerfTest() { Assert.assertTrue(true); return; // disable var now = window.performance ? function () { return window.performance.now(); } : function () { }; console.log("Array test:"); var startTime = now(); var totalRegularArrayTime = 0; var repeats = 1000; var n = 100; var M; for (var k = 0; k < repeats; ++k) { M = new Array(n); for (var i = 0; i < n; ++i) { M[i] = new Array(n); } } var t = now() - startTime; console.log("init = " + t); totalRegularArrayTime += t; startTime = now(); for (var k = 0; k < repeats; ++k) { for (var i = 0; i < n; ++i) { for (var j = 0; j < n; ++j) { M[i][j] = 1; } } } var t = now() - startTime; console.log("write array = " + t); totalRegularArrayTime += t; startTime = now(); for (var k = 0; k < repeats; ++k) { var sum = 0; for (var i = 0; i < n; ++i) { for (var j = 0; j < n; ++j) { sum += M[i][j]; } } //Assert.assertEquals(sum, n * n); } var t = now() - startTime; console.log("read array = " + t); totalRegularArrayTime += t; startTime = now(); Assert.assertTrue(true); var totalTypedArrayTime = 0; console.log("Typed Array test:"); var startTime = now(); for (var k = 0; k < repeats; ++k) { MT = new Float32Array(n * n); } var t = now() - startTime; console.log("init = " + t); totalTypedArrayTime += t; startTime = now(); for (var k = 0; k < repeats; ++k) { for (var i = 0; i < n * n; ++i) { MT[i] = 1; } } var t = now() - startTime; console.log("write array = " + t); totalTypedArrayTime += t; startTime = now(); for (var k = 0; k < repeats; ++k) { var sum = 0; for (var i = 0; i < n * n; ++i) { sum += MT[i]; } //Assert.assertEquals(sum, n * n); } var t = now() - startTime; console.log("read array = " + t); totalTypedArrayTime += t; startTime = now(); Assert.assertTrue(isNaN(totalRegularArrayTime) || totalRegularArrayTime < totalTypedArrayTime, "totalRegularArrayTime=" + totalRegularArrayTime + " totalTypedArrayTime=" + totalTypedArrayTime + " - if this consistently fails then maybe we should switch to typed arrays"); } @Test(description="priority queue test") public void priorityQueueTest() { var q = new PriorityQueue((a, b) -> { return a <= b; }); q.push(42, 5, 23, 5, Math.PI); var u = Math.PI, v; strictEqual(u, q.top()); var cnt = 0; while ((v = q.pop()) !== null) { Assert.assertTrue(u <= v); u = v; ++cnt; } Assert.assertEquals(cnt, 5); q.push(42, 5, 23, 5, Math.PI); var k = q.push(13); strictEqual(Math.PI, q.top()); q.reduceKey(k, 2); u = q.top(); strictEqual(u, 2); cnt = 0; while ((v = q.pop()) !== null) { Assert.assertTrue(u <= v); u = v; ++cnt; } Assert.assertEquals(cnt, 6); } @Test(description="dijkstra") public void dijkstraTest() { // 0 4-3 // \/ / // 1-2 var n = 5; var links = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 1]], getSource = function (l) { return l[0] }, getTarget = function (l) { return l[1] }, getLength = function(l) { return 1 } var calc = new Calculator(n, links, getSource, getTarget, getLength); var d = calc.DistancesFromNode(0); deepEqual(d, [0, 1, 2, 3, 2]); var D = calc.DistanceMatrix(); deepEqual(D, [ [0, 1, 2, 3, 2], [1, 0, 1, 2, 1], [2, 1, 0, 1, 2], [3, 2, 1, 0, 1], [2, 1, 2, 1, 0] ]); } @Test(description="vpsc") public void vpscTest() { var round = function (v, p) { var m = Math.pow(10, p); return Math.round(v * m) / m; }; var rnd = function (a, p) { if (typeof p === "undefined") { p = 4; } return a.map(function (v) { return round(v, p) }) }; var res = function (a, p) { if (typeof p === "undefined") { p = 4; } return a.map(function (v) { return round(v.position(), p) }) }; vpsctestcases.forEach(function (t) { var vs = t.variables.map(function (u, i) { var v; if (typeof u === "number") { v = new Variable(u); } else { v = new Variable(u.desiredPosition, u.weight, u.scale); } v.id = i; return v; }); var cs = t.constraints.map(function (c) { return new Constraint(vs[c.left], vs[c.right], c.gap); }); var solver = new Solver(vs, cs); solver.solve(); if (typeof t.expected !== "undefined") { deepEqual(rnd(t.expected, t.precision), res(vs, t.precision), t.description); } }); } @Test(description="rbtree") public void rbtreeTest() { var tree = new RBTree<Integer>( (a, b) -> { return a - b; }); var data = [5, 8, 3, 1, 7, 6, 2]; data.forEach(function (d) { tree.insert(d); }); var it = tree.iterator(), item; var prev = 0; while ((item = it.next()) !== null) { Assert.assertTrue(prev < item); prev = item; } var m = tree.findIter(5); Assert.assertTrue(m.prev(3)); Assert.assertTrue(m.next(6)); } @Test(description="overlap removal") public void overlapRemovalTest() { var rs = [ new Rectangle(0, 2, 0, 1), new Rectangle(1, 3, 0, 1) ]; Assert.assertEquals(rs[0].overlapX(rs[1]), 1); Assert.assertEquals(rs[0].overlapY(rs[1]), 1); var vs = rs.map((r) -> { return new Variable(r.cx()); }); var cs = VPSC.generateXConstraints(rs, vs); Assert.assertEquals(cs.length, 1); Solver solver = new Solver(vs, cs); solver.solve(); vs.forEach((v, i) -> { rs[i].setXCentre(v.position()); }); Assert.assertEquals(rs[0].overlapX(rs[1]), 0); Assert.assertEquals(rs[0].overlapY(rs[1]), 1); vs = rs.map( (r) -> { return new Variable(r.cy()); }); cs = VPSC.generateYConstraints(rs, vs); Assert.assertEquals(cs.length, 0); } private int overlaps(final Rectangle[] rs) { var cnt = 0; for (var i = 0, n = rs.length; i < n - 1; ++i) { var r1 = rs[i]; for (var j = i + 1; j < n; ++j) { var r2 = rs[j]; if (r1.overlapX(r2) > 0 && r1.overlapY(r2) > 0) { cnt++; } } } return cnt; } @Test(description="cola.vpsc.removeOverlaps") public void removeOverlapsTest() { var rs = [ new Rectangle(0, 4, 0, 4), new Rectangle(3, 5, 1, 2), new Rectangle(1, 3, 3, 5) ]; Assert.assertEquals(overlaps(rs), 2); VPSC.removeOverlaps(rs); Assert.assertEquals(overlaps(rs), 0); Assert.assertEquals(rs[1].y, 1); Assert.assertEquals(rs[1].Y, 2); rs = [ new Rectangle(148.314,303.923,94.4755,161.84969999999998), new Rectangle(251.725,326.6396,20.0193,69.68379999999999), new Rectangle(201.235,263.6349,117.221,236.923), new Rectangle(127.445,193.7047,46.5891,186.5991), new Rectangle(194.259,285.7201,204.182,259.13239999999996) ]; VPSC.removeOverlaps(rs); Assert.assertEquals(overlaps(rs), 0); } @Test(description="packing") public void packingTest() { var nodes = [] for (var i = 0; i < 9; i++) { nodes.push({width: 10, height: 10}) } CoLa.adaptor().nodes(nodes).start(); var check = function (aspectRatioThreshold) { var dim = nodes.reduce(function (p, v) { return { x: Math.min(v.x - v.width / 2, p.x), y: Math.min(v.y - v.height / 2, p.y), X: Math.max(v.x + v.width / 2, p.X), Y: Math.max(v.y + v.height / 2, p.Y) }; }, { x: Double.POSITIVE_INFINITY, X: Double.NEGATIVE_INFINITY, y: Double.POSITIVE_INFINITY, Y: Double.NEGATIVE_INFINITY }); var width = dim.X - dim.x, height = dim.Y - dim.y; Assert.assertTrue(Math.abs(width / height - 1) < aspectRatioThreshold); } check(0.001); // regression test, used to cause infinite loop nodes = [{ width: 24, height: 35 }, { width: 24, height: 35 }, { width: 32, height: 35 }]; CoLa.adaptor().nodes(nodes).start(); check(0.3); // for some reason the first rectangle is offset by the following - no assertion for this yet. PseudoRandom rand = new PseudoRandom(51); for (var i = 0; i < 19; i++) { nodes.push({ width: rand.getNextBetween(5, 30), height: rand.getNextBetween(5, 30) }) } CoLa.adaptor().nodes(nodes).avoidOverlaps(false).start(); check(0.1); } */ }
src/test/java/edu/monash/infotech/marvl/cola/Tests.java
package edu.monash.infotech.marvl.cola; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.MapType; import edu.monash.infotech.marvl.cola.powergraph.Configuration; import edu.monash.infotech.marvl.cola.powergraph.LinkTypeAccessor; import edu.monash.infotech.marvl.cola.powergraph.Module; import edu.monash.infotech.marvl.cola.powergraph.PowerEdge; import edu.monash.infotech.marvl.cola.shortestpaths.Calculator; import edu.monash.infotech.marvl.cola.vpsc.*; import lombok.extern.slf4j.Slf4j; import org.testng.Assert; import org.testng.annotations.*; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.ToDoubleFunction; import java.util.function.ToIntFunction; import java.util.stream.Collectors; @Slf4j public class Tests { private double nodeDistance(final GraphNode u, final GraphNode v) { final double dx = u.x - v.x, dy = u.y - v.y; return Math.sqrt(dx * dx + dy * dy); } private boolean approxEquals(final double actual, final double expected, final double threshold) { return Math.abs(actual - expected) <= threshold; } private List<Link> mapJsonArrayToLinkList(final List<Map<String, Object>> jsonArray) { final List<Link> result = jsonArray.stream().map(jsonObj -> { return new Link(jsonObj.get("source"), jsonObj.get("target")); }).collect(Collectors.toList()); return result; } private List<GraphNode> mapJsonArrayToNodeList(final List<Map<String, Object>> jsonArray) { final List<GraphNode> result = jsonArray.stream().map(jsonObj -> { return new GraphNode(); }).collect(Collectors.toList()); return result; } @Test(description="small power-graph") public void smallPowerGraphTest () { try (final InputStream stream = getClass().getResourceAsStream("/n7e23.json")) { final ObjectMapper mapper = new ObjectMapper(); final MapType type = mapper.getTypeFactory().constructMapType( Map.class, String.class, Object.class); final Map<String, Object> graph = mapper.readValue(stream, type); final int n = ((List)graph.get("nodes")).size(); Assert.assertEquals(n, 7); List<Link> links = mapJsonArrayToLinkList((List<Map<String, Object>>)graph.get("links")); LinkTypeAccessor<Link> linkAccessor = new IntegerLinkAccessor(); Configuration<Link> c = new Configuration<>(n, links, linkAccessor); Assert.assertEquals(c.modules.size(), 7); List<PowerEdge> es = c.allEdges(); Assert.assertEquals(c.R, es.size(), "c.R=" + c.R + ", actual edges in c=" + es.size()); Module m = c.merge(c.modules.get(0), c.modules.get(4)); Assert.assertTrue(m.children.contains(0)); Assert.assertTrue(m.children.contains(4)); Assert.assertTrue(m.outgoing.contains(1)); Assert.assertTrue(m.outgoing.contains(3)); Assert.assertTrue(m.outgoing.contains(5)); Assert.assertTrue(m.outgoing.contains(6)); Assert.assertTrue(m.incoming.contains(2)); Assert.assertTrue(m.incoming.contains(5)); es = c.allEdges(); Assert.assertEquals(c.R, es.size(), "c.R=" + c.R + ", actual edges in c=" + es.size()); m = c.merge(c.modules.get(2), c.modules.get(3)); es = c.allEdges(); Assert.assertEquals(c.R, es.size(), "c.R=" + c.R + ", actual edges in c=" + es.size()); c = new Configuration<>(n, links, linkAccessor); int lastR = c.R; while (c.greedyMerge()) { Assert.assertTrue(c.R < lastR); lastR = c.R; } List<PowerEdge> finalEdges = new ArrayList<>(); List<PowerEdge> powerEdges = c.allEdges(); Assert.assertEquals(powerEdges.size(), 7); List<Group> groups = c.getGroupHierarchy(finalEdges); Assert.assertEquals(groups.size(), 4); } catch (IOException e) { log.error("IOException in smallPowerGraphTest", e); throw new RuntimeException(e); } Assert.assertTrue(true); } @Test(description="all-pairs shortest paths") public void allPairsShortestPathsTest() { LayoutAdaptor d3cola = CoLa.adaptor(); try (final InputStream stream = getClass().getResourceAsStream("/triangle.json")) { final ObjectMapper mapper = new ObjectMapper(); final MapType type = mapper.getTypeFactory().constructMapType( Map.class, String.class, Object.class); final Map<String, Object> graph = mapper.readValue(stream, type); List<Link> links = mapJsonArrayToLinkList((List<Map<String, Object>>)graph.get("links")); List<GraphNode> nodes = mapJsonArrayToNodeList((List<Map<String, Object>>)graph.get("nodes")); d3cola .nodes(nodes) .links(links) .linkDistance(Double.valueOf(1)); final int n = d3cola.nodes().size(); Assert.assertEquals(n, 4); final ToIntFunction<Link> getSourceIndex = (e) -> { return ((Integer)e.source).intValue(); }; final ToIntFunction<Link> getTargetIndex = (e) -> { return ((Integer)e.target).intValue(); }; ToDoubleFunction<Link> getLength = (e) -> { return 1; }; double[][] D = (new Calculator<>(n, d3cola.links(), getSourceIndex, getTargetIndex, getLength)).DistanceMatrix(); Assert.assertEquals(D, new double[][]{ {0, 1, 1, 2}, {1, 0, 1, 2}, {1, 1, 0, 1}, {2, 2, 1, 0}, }); double[] x = new double[]{0, 0, 1, 1}, y = new double[]{1, 0, 0, 1}; Descent descent = new Descent(new double[][]{x, y}, D); double s0 = descent.reduceStress(); double s1 = descent.reduceStress(); Assert.assertTrue(s1 < s0); double s2 = descent.reduceStress(); Assert.assertTrue(s2 < s1); d3cola.start(0,0,10); final List<Double> lengths = d3cola.links().stream().map(l -> { GraphNode u = (GraphNode)l.source, v = (GraphNode)l.target; double dx = u.x - v.x, dy = u.y - v.y; return Math.sqrt(dx*dx + dy*dy); }).collect(Collectors.toList()); Function<List<Double>, Double> avg = (a) -> { return a.stream().reduce( new Double(0), (u, v) -> { return u + v; }) / a.size(); }; final double mean = avg.apply(lengths); final double variance = avg.apply(lengths.stream().map( (l) -> { double d = mean - l; return d * d; }).collect(Collectors.toList())); Assert.assertTrue(variance < 0.1); } catch (IOException e) { log.error("IOException in allPairsShortestPathsTest", e); throw new RuntimeException(e); } Assert.assertTrue(true); } /* @Test(description="edge lengths") public void edgeLengthsTest () { LayoutAdaptor d3cola = CoLa.adaptor(); d3.json("../examples/graphdata/triangle.json", function (error, graph) { var length = function (l) { return Layout.linkId(l) == "2-3" ? 2 : 1; } d3cola .linkDistance(length) .nodes(graph.nodes) .links(graph.links); d3cola.start(100); var errors = graph.links.map((e) -> { var l = nodeDistance(e.source, e.target); return Math.abs(l - length(e)); }), max = Math.max.apply(this, errors); Assert.assertTrue(max < 0.1, "max = " + max); start(); }); Assert.assertTrue(true); } @Test(description="group") public void groupTest () { LayoutAdaptor d3cola = CoLa.adaptor(); var length = (l) -> { return d3cola.linkId(l) == "2-3" ? 2 : 1; } var nodes = []; var u = { x: -5, y: 0, width: 10, height: 10 }; var v = { x: 5, y: 0, width: 10, height: 10 }; var g = { padding: 10, leaves: [0] }; d3cola .linkDistance(length) .avoidOverlaps(true) .nodes([u,v]) .groups([g]); d3cola.start(10, 10, 10); Assert.assertTrue(approxEquals(g.bounds.width(), 30, 0.1)); Assert.assertTrue(approxEquals(g.bounds.height(), 30, 0.1)); Assert.assertTrue(approxEquals(Math.abs(u.y - v.y), 20, 0.1)); } @Test(description="equality constraints") public void equalityConstraintsTest() { LayoutAdaptor d3cola = CoLa.adaptor(); d3.json("../examples/graphdata/triangle.json", function (error, graph) { d3cola .nodes(graph.nodes) .links(graph.links) .constraints([{ type: "separation", axis: "x", left: 0, right: 1, gap: 0, equality: true }, { type: "separation", axis: "y", left: 0, right: 2, gap: 0, equality: true }]); d3cola.start(20, 20, 20); Assert.assertTrue(Math.abs(graph.nodes[0].x - graph.nodes[1].x) < 0.001); Assert.assertTrue(Math.abs(graph.nodes[0].y - graph.nodes[2].y) < 0.001); start(); }); Assert.assertTrue(true); } private int nextInt(final PseudoRandom rand, final int r) { return (int)Math.round(rand.getNext() * r); } @Test(description="convex hulls") public void convexHullsTest() { PseudoRandom rand = new PseudoRandom(); var width = 100, height = 100; for (var k = 0; k < 10; ++k) { var P = []; for (var i = 0; i < 5; ++i) { var p; P.push(p = { x: nextInt(width), y: nextInt(height) }); } var h = Geom.ConvexHull(P); for (var i = 2; i < h.length; ++i) { var p = h[i - 2], q = h[i - 1], r = h[i]; Assert.assertTrue(Geom.isLeft(p, q, r) >= 0, "clockwise hull " + i); for (var j = 0; j < P.length; ++j) { Assert.assertTrue(Geom.isLeft(p, q, P[j]) >= 0, "" + j); } } Assert.assertTrue(h[0] != = h[h.length - 1], "first and last point of hull are different" + k); } } @Test(description="radial sort") public void radialSortTest() { var n = 100; var width = 400, height = 400; var P = []; var x = 0, y = 0; PseudoRandom rand = new PseudoRandom(5); for (var i = 0; i < n; ++i) { var p; P.push(p = { x: nextInt(width), y: nextInt(height) }); x += p.x; y += p.y; } var q = { x: x / n, y: y / n }; //console.log(q); var p0 = null; Geom.clockwiseRadialSweep(q, P, (p, i) -> { if (p0) { var il = Geom.isLeft(q, p0, p); Assert.assertTrue(il >= 0); } p0 = p; }); } private double length(final Point p, final Point q) { final double dx = p.x - q.x, dy = p.y - q.y; return dx * dx + dy * dy; } private Point[] makePoly(final PseudoRandom rand) { return makePoly(rand, 10, 10); } private Point[] makePoly(final PseudoRandom rand, final double width, final double height) { var n = nextInt(rand, 7) + 3; var P = []; loop: for (var i = 0; i < n; ++i) { var p = { x: nextInt(width), y: nextInt(height) }; var ctr = 0; while (i > 0 && length(P[i - 1], p) < 1 // min segment length is 1 || i > 1 && ( // new point must keep poly convex Geom.isLeft(P[i - 2], P[i - 1], p) <= 0 || Geom.isLeft(P[i - 1], p, P[0]) <= 0 || Geom.isLeft(p, P[0], P[1]) <= 0)) { if (ctr++ > 10) break loop; // give up after ten tries (maybe not enough space left for another convex point) p = { x: nextInt(width), y: nextInt(height) }; } P.push(p); } if (P.length > 2) { // must be at least triangular P.push({ x: P[0].x, y: P[0].y }); return P; } return makePoly(rand, width, height); } private List<Point[]> makeNonoverlappingPolys(final PseudoRandom rand, final int n) { var P = []; var overlaps = function (p) { for (var i = 0; i < P.length; i++) { var q = P[i]; if (Geom.polysOverlap(p, q)) return true; } return false; } for (var i = 0; i < n; i++) { var p = makePoly(rand); while (overlaps(p)) { var dx = nextInt(10) - 5, dy = nextInt(10) - 5; p.forEach(function (p) { p.x += dx; p.y += dy; }); } P.push(p); } var minX = 0, minY = 0; P.forEach(function (p) { p.forEach(function (p) { minX = Math.min(minX, p.x); minY = Math.min(minY, p.y); }) }); P.forEach(function (p) { p.forEach(function (p) { p.x -= minX; p.y -= minY; }); }); return P; } private Point midPoint(final Point p) { var mx = 0, my = 0; var n = p.length - 1; for (var i = 0; i < n; i++) { var q = p[i]; mx += q.x; my += q.y; } return { x: mx/n, y: my/n }; } private int countRouteIntersections(routes) { var ints = []; for (var i = 0; i < routes.length - 1; i++) { for (var j = i + 1; j < routes.length ; j++) { var r1 = routes[i], r2 = routes[j]; r1.forEach(function (s1) { r2.forEach(function (s2) { var int = Rectangle.lineIntersection(s1[0].x, s1[0].y, s1[1].x, s1[1].y, s2[0].x, s2[0].y, s2[1].x, s2[1].y); if (int) ints.push(int); }) }) } } return ints.length; } @Test(description="metro crossing min") public void metroCrossingMinTest () { var verts, edges, order, routes; function makeInstance() { verts.forEach(function (v, i) { v.id = i; v.edges = {}; }); edges.forEach(function (e, i) { e.id = i; }); } function twoParallelSegments() { verts = [ { x: 0, y: 10 }, { x: 10, y: 10 } ]; edges = [ [verts[0], verts[1]], [verts[0], verts[1]] ]; makeInstance(); } function threeByThreeSegments() { verts = [ { x: 0, y: 10 }, { x: 10, y: 10 }, { x: 10, y: 20 }, { x: 10, y: 30 }, { x: 20, y: 20 }, { x: 10, y: 0 }, { x: 0, y: 20 } ]; edges = [ [verts[0], verts[1], verts[2], verts[3]], [verts[0], verts[1], verts[2], verts[4]], [verts[5], verts[1], verts[2], verts[6]] ]; makeInstance(); } function regression1() { verts = [ {x:430.79999999999995, y:202.5}, {x:464.4, y:202.5}, {x:464.4, y:261.6666666666667}, {x:464.4, y:320.83333333333337}, {x:474, y:320.83333333333337}, {x:486, y:320.83333333333337}, {x:498.0000000000001, y:202.5}, {x:474, y:202.5}, ]; verts.forEach(function(v) { v.x -= 400; v.y -= 160; v.x /= 4; v.y /= 8; }); edges = [[ verts[0], verts[1], verts[2], verts[3], verts[4], verts[5] ], [ verts[6], verts[7], verts[1], verts[0] ]]; makeInstance(); } function nudge() { order = GridRouter.orderEdges(edges); routes = edges.map((e) -> { return GridRouter.makeSegments(e); }); GridRouter.nudgeSegments(routes, 'x', 'y', order, 2); GridRouter.nudgeSegments(routes, 'y', 'x', order, 2); GridRouter.unreverseEdges(routes, edges); } // trivial case twoParallelSegments(); nudge(); // two segments, one reversed edges[1].reverse(); nudge(); threeByThreeSegments(); var lcs = new ongestCommonSubsequence('ABAB'.split(''), 'DABA'.split('')); deepEqual(lcs.getSequence(), 'ABA'.split('')); lcs = new LongestCommonSubsequence(edges[0], edges[1]); Assert.assertEquals(lcs.length, 3); deepEqual(lcs.getSequence().map((v) -> { return v.id }), [0, 1, 2]); var e0reversed = edges[0].slice(0).reverse(); lcs = new LongestCommonSubsequence(e0reversed, edges[1]); deepEqual(lcs.getSequence().map((v) -> { return v.id }), [2, 1, 0]); Assert.assertTrue(lcs.reversed); nudge(); Assert.assertEquals(routes[0].length, 2); Assert.assertEquals(routes[1].length, 3); Assert.assertEquals(routes[2].length, 2); Assert.assertEquals(countRouteIntersections(routes), 2); // flip it in y and try again threeByThreeSegments(); verts.forEach( (v) -> { v.y = 30 - v.y }); nudge(); Assert.assertEquals(countRouteIntersections(routes), 2); // reverse the first edge path and see what happens threeByThreeSegments(); edges[0].reverse(); nudge(); Assert.assertEquals(countRouteIntersections(routes), 2); // reverse the second edge path threeByThreeSegments(); edges[1].reverse(); nudge(); Assert.assertEquals(countRouteIntersections(routes), 2); // reverse the first 2 edge paths threeByThreeSegments(); edges[0].reverse(); edges[1].reverse(); nudge(); Assert.assertEquals(countRouteIntersections(routes), 2); regression1(); nudge(); Assert.assertEquals(countRouteIntersections(routes), 0); } // next steps: // o label node and group centre and boundary vertices // - non-traversable regions (obstacles) are determined by finding the highest common ancestors of the source and target nodes // - to route each edge the weights of the edges are adjusted such that those inside obstacles // have infinite weight while those inside the source and target node have zero weight // - augment dijkstra with a cost for bends @Test(description="grid router") public void gridRouterTest() { d3.json("../examples/graphdata/tetrisbugmultiedgeslayout.json", function (error, graph) { var gridrouter = new GridRouter(graph.nodes,{ getChildren: function(v) { return v.children; }, getBounds: function(v) { return typeof v.bounds !== 'undefined' ? new Rectangle(v.bounds.x, v.bounds.X, v.bounds.y, v.bounds.Y) : undefined; } }); var source = 1, target = 2; var shortestPath = gridrouter.route(source, target); function check(expected) { Assert.assertTrue(gridrouter.obstacles.length == expected); Assert.assertTrue(gridrouter.obstacles.map((v) -> { return v.id }).indexOf(source) < 0); Assert.assertTrue(gridrouter.obstacles.map((v) -> { return v.id }).indexOf(target) < 0); } check(8); source = 0, target = 7; shortestPath = gridrouter.route(source, target); check(6); source = 4, target = 5; shortestPath = gridrouter.route(source, target); check(8); source = 11, target = 2; shortestPath = gridrouter.route(source, target); check(13); // group to node source = 16, target = 5; shortestPath = gridrouter.route(source, target); check(7); // bend minimal? source = 1, target = 2; shortestPath = gridrouter.route(source, target); start(); }); Assert.assertTrue(true); } @Test(description="shortest path with bends") public void shortestPathWithBendsTest() { // 0 - 1 - 2 // | | // 3 - 4 var nodes = [[0,0],[1,0],[2,0],[1,1],[2,1]]; var edges = [[0,1,1],[1,2,2],[1,3,1],[3,4,1],[2,4,2]]; function source(e) { return e[0]}; function target(e) { return e[1]}; function length(e) { return e[2]}; Calculator sp = new Calculator(nodes.length, edges, source, target, length); var path = sp.PathFromNodeToNodeWithPrevCost(0, 4, function (u,v,w){ var a = nodes[u], b = nodes[v], c = nodes[w]; var dx = Math.abs(c[0] - a[0]), dy = Math.abs(c[1] - a[1]); return dx > 0.01 && dy > 0.01 ? 1000 : 0; }); Assert.assertTrue(true); } @Test(description="tangent visibility graph") public void tangentVisibilityGraphTest() { for (var tt = 0; tt < 100; tt++) { PseudoRandom rand = new PseudoRandom(tt); nextInt = function (r) { return Math.round(rand.getNext() * r) }, n = 10, P = makeNonoverlappingPolys(rand, n), port1 = midPoint(P[8]), port2 = midPoint(P[9]); TangentVisibilityGraph g = new TangentVisibilityGraph(P); start = g.addPoint(port1, 8), end = g.addPoint(port2, 9); g.addEdgeIfVisible(port1, port2, 8, 9); var getSource = function (e) { return e.source.id }, getTarget = function(e) { return e.target.id}, getLength = function(e) { return e.length() } shortestPath = (new Calculator(g.V.length, g.E, getSource, getTarget, getLength)).PathFromNodeToNode(start.id, end.id); Assert.assertTrue(shortestPath.length > 0); } Assert.assertTrue(true); } @Test(description="tangents") public void tangentsTest() { PseudoRandom rand = new PseudoRandom(); var rect = [{ x: 10, y: 10 }, { x: 20, y: 10 }, { x: 10, y: 20 }, { x: 20, y: 20 }]; var pnt = [{ x: 0, y: 0 }]; var t1 = Geom.tangents(pnt, rect); for (var j = 0; j < 100; j++) { var A = makePoly(rand), B = makePoly(rand); B.forEach((p) -> { p.x += 11 }); //if (j !== 207) continue; var t = Geom.tangents(A, B); // ok(t.length === 4, t.length + " tangents found at j="+j); } Assert.assertTrue(true); } function intersects(l, P) { var ints = []; for (var i = 1; i < P.length; ++i) { var int = Rectangle.lineIntersection( l.x1, l.y1, l.x2, l.y2, P[i-1].x, P[i-1].y, P[i].x, P[i].y ); if (int) ints.push(int); } return ints; } @Test(description="pseudo random number test") public void pseudoRandomNumberTest() { PseudoRandom rand = new PseudoRandom(); for (var i = 0; i < 100; ++i) { var r = rand.getNext(); Assert.assertTrue(r <= 1, "r=" + r); Assert.assertTrue(r >= 0, "r=" + r); r = rand.getNextBetween(5, 10); Assert.assertTrue(r <= 10, "r=" + r); Assert.assertTrue(r >= 5, "r=" + r); r = rand.getNextBetween(-5, 0); Assert.assertTrue(r <= 0, "r=" + r); Assert.assertTrue(r >= -5, "r=" + r); //console.log(r); } } @Test(description="rectangle intersections") public void rectangleIntersectionsTest() { var r = new Rectangle(2, 4, 0, 2); var p = r.rayIntersection(0, 1); Assert.assertTrue(p.x == 2); Assert.assertTrue(p.y == 1); p = r.rayIntersection(0, 0); Assert.assertTrue(p.x == 2); } @Test(description="matrix perf test") public void matrixPerfTest() { Assert.assertTrue(true); return; // disable var now = window.performance ? function () { return window.performance.now(); } : function () { }; console.log("Array test:"); var startTime = now(); var totalRegularArrayTime = 0; var repeats = 1000; var n = 100; var M; for (var k = 0; k < repeats; ++k) { M = new Array(n); for (var i = 0; i < n; ++i) { M[i] = new Array(n); } } var t = now() - startTime; console.log("init = " + t); totalRegularArrayTime += t; startTime = now(); for (var k = 0; k < repeats; ++k) { for (var i = 0; i < n; ++i) { for (var j = 0; j < n; ++j) { M[i][j] = 1; } } } var t = now() - startTime; console.log("write array = " + t); totalRegularArrayTime += t; startTime = now(); for (var k = 0; k < repeats; ++k) { var sum = 0; for (var i = 0; i < n; ++i) { for (var j = 0; j < n; ++j) { sum += M[i][j]; } } //Assert.assertEquals(sum, n * n); } var t = now() - startTime; console.log("read array = " + t); totalRegularArrayTime += t; startTime = now(); Assert.assertTrue(true); var totalTypedArrayTime = 0; console.log("Typed Array test:"); var startTime = now(); for (var k = 0; k < repeats; ++k) { MT = new Float32Array(n * n); } var t = now() - startTime; console.log("init = " + t); totalTypedArrayTime += t; startTime = now(); for (var k = 0; k < repeats; ++k) { for (var i = 0; i < n * n; ++i) { MT[i] = 1; } } var t = now() - startTime; console.log("write array = " + t); totalTypedArrayTime += t; startTime = now(); for (var k = 0; k < repeats; ++k) { var sum = 0; for (var i = 0; i < n * n; ++i) { sum += MT[i]; } //Assert.assertEquals(sum, n * n); } var t = now() - startTime; console.log("read array = " + t); totalTypedArrayTime += t; startTime = now(); Assert.assertTrue(isNaN(totalRegularArrayTime) || totalRegularArrayTime < totalTypedArrayTime, "totalRegularArrayTime=" + totalRegularArrayTime + " totalTypedArrayTime=" + totalTypedArrayTime + " - if this consistently fails then maybe we should switch to typed arrays"); } @Test(description="priority queue test") public void priorityQueueTest() { var q = new PriorityQueue((a, b) -> { return a <= b; }); q.push(42, 5, 23, 5, Math.PI); var u = Math.PI, v; strictEqual(u, q.top()); var cnt = 0; while ((v = q.pop()) !== null) { Assert.assertTrue(u <= v); u = v; ++cnt; } Assert.assertEquals(cnt, 5); q.push(42, 5, 23, 5, Math.PI); var k = q.push(13); strictEqual(Math.PI, q.top()); q.reduceKey(k, 2); u = q.top(); strictEqual(u, 2); cnt = 0; while ((v = q.pop()) !== null) { Assert.assertTrue(u <= v); u = v; ++cnt; } Assert.assertEquals(cnt, 6); } @Test(description="dijkstra") public void dijkstraTest() { // 0 4-3 // \/ / // 1-2 var n = 5; var links = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 1]], getSource = function (l) { return l[0] }, getTarget = function (l) { return l[1] }, getLength = function(l) { return 1 } var calc = new Calculator(n, links, getSource, getTarget, getLength); var d = calc.DistancesFromNode(0); deepEqual(d, [0, 1, 2, 3, 2]); var D = calc.DistanceMatrix(); deepEqual(D, [ [0, 1, 2, 3, 2], [1, 0, 1, 2, 1], [2, 1, 0, 1, 2], [3, 2, 1, 0, 1], [2, 1, 2, 1, 0] ]); } @Test(description="vpsc") public void vpscTest() { var round = function (v, p) { var m = Math.pow(10, p); return Math.round(v * m) / m; }; var rnd = function (a, p) { if (typeof p === "undefined") { p = 4; } return a.map(function (v) { return round(v, p) }) }; var res = function (a, p) { if (typeof p === "undefined") { p = 4; } return a.map(function (v) { return round(v.position(), p) }) }; vpsctestcases.forEach(function (t) { var vs = t.variables.map(function (u, i) { var v; if (typeof u === "number") { v = new Variable(u); } else { v = new Variable(u.desiredPosition, u.weight, u.scale); } v.id = i; return v; }); var cs = t.constraints.map(function (c) { return new Constraint(vs[c.left], vs[c.right], c.gap); }); var solver = new Solver(vs, cs); solver.solve(); if (typeof t.expected !== "undefined") { deepEqual(rnd(t.expected, t.precision), res(vs, t.precision), t.description); } }); } @Test(description="rbtree") public void rbtreeTest() { var tree = new RBTree<Integer>( (a, b) -> { return a - b; }); var data = [5, 8, 3, 1, 7, 6, 2]; data.forEach(function (d) { tree.insert(d); }); var it = tree.iterator(), item; var prev = 0; while ((item = it.next()) !== null) { Assert.assertTrue(prev < item); prev = item; } var m = tree.findIter(5); Assert.assertTrue(m.prev(3)); Assert.assertTrue(m.next(6)); } @Test(description="overlap removal") public void overlapRemovalTest() { var rs = [ new Rectangle(0, 2, 0, 1), new Rectangle(1, 3, 0, 1) ]; Assert.assertEquals(rs[0].overlapX(rs[1]), 1); Assert.assertEquals(rs[0].overlapY(rs[1]), 1); var vs = rs.map((r) -> { return new Variable(r.cx()); }); var cs = VPSC.generateXConstraints(rs, vs); Assert.assertEquals(cs.length, 1); Solver solver = new Solver(vs, cs); solver.solve(); vs.forEach((v, i) -> { rs[i].setXCentre(v.position()); }); Assert.assertEquals(rs[0].overlapX(rs[1]), 0); Assert.assertEquals(rs[0].overlapY(rs[1]), 1); vs = rs.map( (r) -> { return new Variable(r.cy()); }); cs = VPSC.generateYConstraints(rs, vs); Assert.assertEquals(cs.length, 0); } private int overlaps(final Rectangle[] rs) { var cnt = 0; for (var i = 0, n = rs.length; i < n - 1; ++i) { var r1 = rs[i]; for (var j = i + 1; j < n; ++j) { var r2 = rs[j]; if (r1.overlapX(r2) > 0 && r1.overlapY(r2) > 0) { cnt++; } } } return cnt; } @Test(description="cola.vpsc.removeOverlaps") public void removeOverlapsTest() { var rs = [ new Rectangle(0, 4, 0, 4), new Rectangle(3, 5, 1, 2), new Rectangle(1, 3, 3, 5) ]; Assert.assertEquals(overlaps(rs), 2); VPSC.removeOverlaps(rs); Assert.assertEquals(overlaps(rs), 0); Assert.assertEquals(rs[1].y, 1); Assert.assertEquals(rs[1].Y, 2); rs = [ new Rectangle(148.314,303.923,94.4755,161.84969999999998), new Rectangle(251.725,326.6396,20.0193,69.68379999999999), new Rectangle(201.235,263.6349,117.221,236.923), new Rectangle(127.445,193.7047,46.5891,186.5991), new Rectangle(194.259,285.7201,204.182,259.13239999999996) ]; VPSC.removeOverlaps(rs); Assert.assertEquals(overlaps(rs), 0); } @Test(description="packing") public void packingTest() { var nodes = [] for (var i = 0; i < 9; i++) { nodes.push({width: 10, height: 10}) } CoLa.adaptor().nodes(nodes).start(); var check = function (aspectRatioThreshold) { var dim = nodes.reduce(function (p, v) { return { x: Math.min(v.x - v.width / 2, p.x), y: Math.min(v.y - v.height / 2, p.y), X: Math.max(v.x + v.width / 2, p.X), Y: Math.max(v.y + v.height / 2, p.Y) }; }, { x: Double.POSITIVE_INFINITY, X: Double.NEGATIVE_INFINITY, y: Double.POSITIVE_INFINITY, Y: Double.NEGATIVE_INFINITY }); var width = dim.X - dim.x, height = dim.Y - dim.y; Assert.assertTrue(Math.abs(width / height - 1) < aspectRatioThreshold); } check(0.001); // regression test, used to cause infinite loop nodes = [{ width: 24, height: 35 }, { width: 24, height: 35 }, { width: 32, height: 35 }]; CoLa.adaptor().nodes(nodes).start(); check(0.3); // for some reason the first rectangle is offset by the following - no assertion for this yet. PseudoRandom rand = new PseudoRandom(51); for (var i = 0; i < 19; i++) { nodes.push({ width: rand.getNextBetween(5, 30), height: rand.getNextBetween(5, 30) }) } CoLa.adaptor().nodes(nodes).avoidOverlaps(false).start(); check(0.1); } */ }
remove annoying BOM
src/test/java/edu/monash/infotech/marvl/cola/Tests.java
remove annoying BOM
Java
mit
1ad72d3e0accf4f5f05e9a4ef3ee8e9597ac2185
0
epochcoder/jsoup,epochcoder/jsoup
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.Map; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void up() { Document doc = Jsoup.parse(reference); Element div2 = doc.getElementById("div2"); assertNotNull(div2); Element div1 = div2.up("div#div1"); assertNotNull(div1); assertEquals("div1", div1.id()); Element invalid = div2.up("img.invalid"); assertNull(invalid); } @Test public void down() { Document doc = Jsoup.parse(reference); Element div1 = doc.getElementById("div1"); assertNotNull(div1); Element el = div1.down("div#div2 > img[src^=foo]"); assertNotNull(el); assertEquals("img", el.tagName().toLowerCase()); assertEquals("foo.png", el.attr("src")); } @Test public void next() { Document doc = Jsoup.parse(reference); Elements ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); Element el = ps.first().next("div#div2"); assertNotNull(el); assertEquals("div2", el.id()); } @Test public void previous() { Document doc = Jsoup.parse(reference); Element div2 = doc.getElementById("div2"); assertNotNull(div2); Element el = div2.previous("p + p"); assertNotNull(el); assertEquals("Another element", el.text()); } @Test public void chained() { Document doc = Jsoup.parse(reference); Element div1 = doc.getElementById("div1"); assertNotNull(div1); Element el = div1 .down("img") .up("div") .previous("p") .previous("p") .next("p") .down("b"); assertNotNull(el); assertEquals("element", el.text()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class='mellow yellow'>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); assertFalse(doc.hasClass("mellow")); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\"><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("class", "second").text("now"); assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><p class=\"second\">now</p></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\">", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\">", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<Node>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4", ""); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } }
src/test/java/org/jsoup/nodes/ElementTest.java
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.helper.StringUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.Map; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class='mellow yellow'>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); assertFalse(doc.hasClass("mellow")); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\"><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("class", "second").text("now"); assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><p class=\"second\">now</p></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\">", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\">", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<Node>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4", ""); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } }
* tests for dom navigation methods (up/down/previous/next)
src/test/java/org/jsoup/nodes/ElementTest.java
* tests for dom navigation methods (up/down/previous/next)
Java
mit
4631e4615f8acc2f768ba01bf909c96382df0a25
0
AvaIre/AvaIre,AvaIre/AvaIre
/* * Copyright (c) 2019. * * This file is part of AvaIre. * * AvaIre is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AvaIre 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 AvaIre. If not, see <https://www.gnu.org/licenses/>. * * */ package com.avairebot.time; import com.avairebot.BaseTest; import org.junit.Test; import java.text.ParseException; import static org.junit.jupiter.api.Assertions.assertEquals; public class CarbonFormatsTests extends BaseTest { @Test public void testCarbonParsesDateTimeFormatsCorrectly() throws ParseException { Carbon format = Carbon.createFromFormat(Formats.DATE_TIME.getFormat(), "2019-01-13 19:37:59"); assertEquals(2019, format.getYear()); assertEquals(1, format.getMonth()); assertEquals(13, format.getDay()); assertEquals(19, format.getHour()); assertEquals(37, format.getMinute()); assertEquals(59, format.getSecond()); } @Test public void testCarbonDateTimeStringIsGeneratedCorrectly() throws ParseException { assertEquals("2019-01-13 19:37:59", Carbon.createFromFormat( Formats.DATE_TIME.getFormat(), "2019-01-13 19:37:59" ).toDateTimeString()); } @Test public void testCarbonParsesDateFormatsCorrectly() throws ParseException { Carbon format = Carbon.createFromFormat(Formats.DATE.getFormat(), "2019-01-13"); assertEquals(2019, format.getYear()); assertEquals(1, format.getMonth()); assertEquals(13, format.getDay()); assertEquals(0, format.getHour()); assertEquals(0, format.getMinute()); assertEquals(0, format.getSecond()); } @Test public void testCarbonDateStringIsGeneratedCorrectly() throws ParseException { assertEquals("2019-01-13", Carbon.createFromFormat( Formats.DATE.getFormat(), "2019-01-13" ).toDateString()); } @Test public void testCarbonParsesFormattedDateFormatsCorrectly() throws ParseException { Carbon format = Carbon.createFromFormat(Formats.FORMATTED_DATE.getFormat(), "Jan 13, 2019"); assertEquals(2019, format.getYear()); assertEquals(1, format.getMonth()); assertEquals(13, format.getDay()); assertEquals(0, format.getHour()); assertEquals(0, format.getMinute()); assertEquals(0, format.getSecond()); } @Test public void testCarbonFormattedDateStringIsGeneratedCorrectly() throws ParseException { assertEquals("Jan 13, 2019", Carbon.createFromFormat( Formats.FORMATTED_DATE.getFormat(), "Jan 13, 2019" ).toFormattedDateString()); } @Test public void testCarbonParsesTimeFormatsCorrectly() throws ParseException { Carbon format = Carbon.createFromFormat(Formats.TIME.getFormat(), "19:37:59"); assertEquals(1970, format.getYear()); assertEquals(1, format.getMonth()); assertEquals(1, format.getDay()); assertEquals(19, format.getHour()); assertEquals(37, format.getMinute()); assertEquals(59, format.getSecond()); } @Test public void testCarbonTimeStringIsGeneratedCorrectly() throws ParseException { assertEquals("19:37:59", Carbon.createFromFormat( Formats.TIME.getFormat(), "19:37:59" ).toTimeString()); } @Test public void testCarbonParsesDayDateTimeCorrectly() throws ParseException { Carbon format = Carbon.createFromFormat(Formats.DAY_DATE_TIME.getFormat(), "Sun, Jan 13, 2019 7:37 PM"); assertEquals(2019, format.getYear()); assertEquals(13, format.getDay()); assertEquals(19, format.getHour()); assertEquals(37, format.getMinute()); assertEquals(0, format.getSecond()); } @Test public void testCarbonDayDateTimeStringIsGeneratedCorrectly() throws ParseException { // Windows likes to make the "PM" lowercase, while any other distribution wants // to make it upper case, to make the test pass regardless of OS we're just // forcing it into lowercase here so we can check the end result without // caring about letter casing. assertEquals("sun, jan 13, 2019 7:37 pm", Carbon.createFromFormat( Formats.DAY_DATE_TIME.getFormat(), "Sun, Jan 13, 2019 7:37 PM" ).toDayDateTimeString().toLowerCase()); } }
src/test/java/com/avairebot/time/CarbonFormatsTests.java
/* * Copyright (c) 2019. * * This file is part of AvaIre. * * AvaIre is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AvaIre 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 AvaIre. If not, see <https://www.gnu.org/licenses/>. * * */ package com.avairebot.time; import com.avairebot.BaseTest; import org.junit.Test; import java.text.ParseException; import static org.junit.jupiter.api.Assertions.assertEquals; public class CarbonFormatsTests extends BaseTest { @Test public void testCarbonParsesDateTimeFormatsCorrectly() throws ParseException { Carbon format = Carbon.createFromFormat(Formats.DATE_TIME.getFormat(), "2019-01-13 19:37:59"); assertEquals(2019, format.getYear()); assertEquals(1, format.getMonth()); assertEquals(13, format.getDay()); assertEquals(19, format.getHour()); assertEquals(37, format.getMinute()); assertEquals(59, format.getSecond()); } @Test public void testCarbonDateTimeStringIsGeneratedCorrectly() throws ParseException { assertEquals("2019-01-13 19:37:59", Carbon.createFromFormat( Formats.DATE_TIME.getFormat(), "2019-01-13 19:37:59" ).toDateTimeString()); } @Test public void testCarbonParsesDateFormatsCorrectly() throws ParseException { Carbon format = Carbon.createFromFormat(Formats.DATE.getFormat(), "2019-01-13"); assertEquals(2019, format.getYear()); assertEquals(1, format.getMonth()); assertEquals(13, format.getDay()); assertEquals(0, format.getHour()); assertEquals(0, format.getMinute()); assertEquals(0, format.getSecond()); } @Test public void testCarbonDateStringIsGeneratedCorrectly() throws ParseException { assertEquals("2019-01-13", Carbon.createFromFormat( Formats.DATE.getFormat(), "2019-01-13" ).toDateString()); } @Test public void testCarbonParsesFormattedDateFormatsCorrectly() throws ParseException { Carbon format = Carbon.createFromFormat(Formats.FORMATTED_DATE.getFormat(), "Jan 13, 2019"); assertEquals(2019, format.getYear()); assertEquals(1, format.getMonth()); assertEquals(13, format.getDay()); assertEquals(0, format.getHour()); assertEquals(0, format.getMinute()); assertEquals(0, format.getSecond()); } @Test public void testCarbonFormattedDateStringIsGeneratedCorrectly() throws ParseException { assertEquals("Jan 13, 2019", Carbon.createFromFormat( Formats.FORMATTED_DATE.getFormat(), "Jan 13, 2019" ).toFormattedDateString()); } @Test public void testCarbonParsesTimeFormatsCorrectly() throws ParseException { Carbon format = Carbon.createFromFormat(Formats.TIME.getFormat(), "19:37:59"); assertEquals(1970, format.getYear()); assertEquals(1, format.getMonth()); assertEquals(1, format.getDay()); assertEquals(19, format.getHour()); assertEquals(37, format.getMinute()); assertEquals(59, format.getSecond()); } @Test public void testCarbonTimeStringIsGeneratedCorrectly() throws ParseException { assertEquals("19:37:59", Carbon.createFromFormat( Formats.TIME.getFormat(), "19:37:59" ).toTimeString()); } @Test public void testCarbonParsesDayDateTimeCorrectly() throws ParseException { Carbon format = Carbon.createFromFormat(Formats.DAY_DATE_TIME.getFormat(), "Sun, Jan 13, 2019 7:37 PM"); assertEquals(2019, format.getYear()); assertEquals(13, format.getDay()); assertEquals(19, format.getHour()); assertEquals(37, format.getMinute()); assertEquals(0, format.getSecond()); } @Test public void testCarbonDayDateTimeStringIsGeneratedCorrectly() throws ParseException { assertEquals("Sun, Jan 13, 2019 7:37 pm", Carbon.createFromFormat( Formats.DAY_DATE_TIME.getFormat(), "Sun, Jan 13, 2019 7:37 PM" ).toDayDateTimeString()); } }
Make date time string test ignore letter casing This fixes a bug where Windows wants the "AM" and "PM" to be lowercase, and any other distribution wants it to be upper case, so the test fails if you're not compiling/testing on a windows OS, this commit fixes that by only checking the lowercase version.
src/test/java/com/avairebot/time/CarbonFormatsTests.java
Make date time string test ignore letter casing
Java
lgpl-2.1
75e9c7240da26706aa8641c882f896af0411b12d
0
heather9911/flies,google-code-export/flies,google-code-export/flies,heather9911/flies,google-code-export/flies,heather9911/flies,google-code-export/flies,heather9911/flies
package org.fedorahosted.flies.webtrans.editor.table; import static org.fedorahosted.flies.webtrans.editor.table.TableConstants.MAX_PAGE_ROW; import java.util.List; import net.customware.gwt.dispatch.client.DispatchAsync; import net.customware.gwt.presenter.client.EventBus; import net.customware.gwt.presenter.client.place.Place; import net.customware.gwt.presenter.client.place.PlaceRequest; import net.customware.gwt.presenter.client.widget.WidgetDisplay; import org.fedorahosted.flies.common.ContentState; import org.fedorahosted.flies.common.EditState; import org.fedorahosted.flies.gwt.auth.AuthenticationError; import org.fedorahosted.flies.gwt.auth.AuthorizationError; import org.fedorahosted.flies.gwt.model.DocumentId; import org.fedorahosted.flies.gwt.model.TransUnit; import org.fedorahosted.flies.gwt.model.TransUnitId; import org.fedorahosted.flies.gwt.rpc.EditingTranslationAction; import org.fedorahosted.flies.gwt.rpc.EditingTranslationResult; import org.fedorahosted.flies.gwt.rpc.GetTransUnits; import org.fedorahosted.flies.gwt.rpc.GetTransUnitsResult; import org.fedorahosted.flies.gwt.rpc.UpdateTransUnit; import org.fedorahosted.flies.gwt.rpc.UpdateTransUnitResult; import org.fedorahosted.flies.webtrans.client.DocumentSelectionEvent; import org.fedorahosted.flies.webtrans.client.DocumentSelectionHandler; import org.fedorahosted.flies.webtrans.client.NavTransUnitEvent; import org.fedorahosted.flies.webtrans.client.NavTransUnitHandler; import org.fedorahosted.flies.webtrans.client.NotificationEvent; import org.fedorahosted.flies.webtrans.client.TransMemoryCopyEvent; import org.fedorahosted.flies.webtrans.client.TransMemoryCopyHandler; import org.fedorahosted.flies.webtrans.client.WorkspaceContext; import org.fedorahosted.flies.webtrans.client.NotificationEvent.Severity; import org.fedorahosted.flies.webtrans.client.auth.Identity; import org.fedorahosted.flies.webtrans.client.events.TransUnitEditEvent; import org.fedorahosted.flies.webtrans.client.events.TransUnitEditEventHandler; import org.fedorahosted.flies.webtrans.client.events.TransUnitUpdatedEvent; import org.fedorahosted.flies.webtrans.client.events.TransUnitUpdatedEventHandler; import org.fedorahosted.flies.webtrans.client.rpc.CachingDispatchAsync; import org.fedorahosted.flies.webtrans.editor.DocumentEditorPresenter; import org.fedorahosted.flies.webtrans.editor.HasPageNavigation; import org.fedorahosted.flies.webtrans.editor.filter.ContentFilter; import org.fedorahosted.flies.webtrans.editor.filter.FilterDisabledEvent; import org.fedorahosted.flies.webtrans.editor.filter.FilterDisabledEventHandler; import org.fedorahosted.flies.webtrans.editor.filter.FilterEnabledEvent; import org.fedorahosted.flies.webtrans.editor.filter.FilterEnabledEventHandler; import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.event.logical.shared.HasSelectionHandlers; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.gen2.event.shared.HandlerRegistration; import com.google.gwt.gen2.table.client.TableModel; import com.google.gwt.gen2.table.client.TableModel.Callback; import com.google.gwt.gen2.table.client.TableModelHelper.Request; import com.google.gwt.gen2.table.client.TableModelHelper.SerializableResponse; import com.google.gwt.gen2.table.event.client.HasPageChangeHandlers; import com.google.gwt.gen2.table.event.client.HasPageCountChangeHandlers; import com.google.gwt.gen2.table.event.client.PageChangeHandler; import com.google.gwt.gen2.table.event.client.PageCountChangeHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.inject.Inject; public class TableEditorPresenter extends DocumentEditorPresenter<TableEditorPresenter.Display> implements HasPageNavigation, HasPageChangeHandlers, HasPageCountChangeHandlers { public static final Place PLACE = new Place("TableEditor"); public interface Display extends WidgetDisplay, HasPageNavigation { HasSelectionHandlers<TransUnit> getSelectionHandlers(); HasPageChangeHandlers getPageChangeHandlers(); HasPageCountChangeHandlers getPageCountChangeHandlers(); RedirectingCachedTableModel<TransUnit> getTableModel(); void setTableModelHandler(TableModelHandler<TransUnit> hadler); void reloadPage(); void setPageSize(int size); void setContentFilter(ContentFilter<TransUnit> filter); void clearContentFilter(); void gotoRow(int row); int getCurrentPageNumber(); TransUnit getTransUnitValue(int row); InlineTargetCellEditor getTargetCellEditor(); List<TransUnit> getRowValues(); int getCurrentPage(); int getPageSize(); } private DocumentId documentId; private final DispatchAsync dispatcher; private final WorkspaceContext workspaceContext; private final Identity identity; @Inject public TableEditorPresenter(final Display display, final EventBus eventBus, final CachingDispatchAsync dispatcher,final Identity identity, final WorkspaceContext workspaceContext) { super(display, eventBus); this.dispatcher = dispatcher; this.workspaceContext = workspaceContext; this.identity = identity; } @Override public Place getPlace() { return PLACE; } private TransUnit selectedTransUnit; @Override protected void onBind() { display.setTableModelHandler(tableModelHandler); display.setPageSize(TableConstants.PAGE_SIZE); registerHandler(display.getSelectionHandlers().addSelectionHandler(new SelectionHandler<TransUnit>() { @Override public void onSelection(SelectionEvent<TransUnit> event) { if(event.getSelectedItem() != selectedTransUnit) { selectedTransUnit = event.getSelectedItem(); //startEditing(selectedTransUnit); eventBus.fireEvent(event); } } })); registerHandler( eventBus.addHandler(DocumentSelectionEvent.getType(), new DocumentSelectionHandler() { @Override public void onDocumentSelected(DocumentSelectionEvent event) { if(!event.getDocumentId().equals(documentId)) { documentId = event.getDocumentId(); display.getTableModel().clearCache(); display.getTableModel().setRowCount(TableModel.UNKNOWN_ROW_COUNT); display.gotoPage(0, true); } } }) ); registerHandler(eventBus.addHandler(FilterEnabledEvent.getType(), new FilterEnabledEventHandler() { @Override public void onFilterEnabled(FilterEnabledEvent event) { display.setContentFilter(event.getContentFilter()); } })); registerHandler(eventBus.addHandler(FilterDisabledEvent.getType(), new FilterDisabledEventHandler() { @Override public void onFilterDisabled(FilterDisabledEvent event) { display.clearContentFilter(); } })); registerHandler(eventBus.addHandler(TransUnitUpdatedEvent.getType(), new TransUnitUpdatedEventHandler() { @Override public void onTransUnitUpdated(TransUnitUpdatedEvent event) { if(documentId != null && documentId.equals(event.getDocumentId())) { if(selectedTransUnit != null && selectedTransUnit.getId().equals(event.getTransUnitId())) { // handle change in current selection //eventBus.fireEvent(new NotificationEvent(Severity.Warning, "Someone else updated this translation unit. you're in trouble...")); //display.getTableModel().setRowValue(row, rowValue); } boolean reloadPage = true; if (reloadPage) { display.getTableModel().clearCache(); display.reloadPage(); } else { final Integer rowOffset = getRowOffset(event.getTransUnitId()); // - add TU index to model if (rowOffset != null) { final int row = display.getCurrentPage() * display.getPageSize() + rowOffset; Log.info("row calculated as "+row); dispatcher.execute(new GetTransUnits( documentId, workspaceContext.getLocaleId(), row, 1), new AsyncCallback<GetTransUnitsResult>() { @Override public void onFailure(Throwable e) { Log.error(e.getMessage(), e); } @Override public void onSuccess(GetTransUnitsResult result) { // FIXME should this be row, rowOffset, or something else? display.getTableModel().setRowValueOverride(row, result.getUnits().get(0)); } }); } else { display.getTableModel().clearCache(); } } } } })); registerHandler(eventBus.addHandler(TransUnitEditEvent.getType(), new TransUnitEditEventHandler() { @Override public void onTransUnitEdit(TransUnitEditEvent event) { if(documentId != null && documentId.equals(event.getDocumentId())) { if(selectedTransUnit != null && selectedTransUnit.getId().equals(event.getTransUnitId())) { // handle change in current selection if(!event.getSessionId().equals(identity.getSessionId())) eventBus.fireEvent(new NotificationEvent(Severity.Warning, "Warning: This Translation Unit is being edited by someone else.")); } //display.getTableModel().clearCache(); //display.reloadPage(); } } })); registerHandler(eventBus.addHandler(NavTransUnitEvent.getType(), new NavTransUnitHandler() { @Override public void onNavTransUnit(NavTransUnitEvent event) { if(selectedTransUnit != null) { int step = event.getStep(); //Send message to server to stop editing current selection //stopEditing(selectedTransUnit); InlineTargetCellEditor editor = display.getTargetCellEditor(); //If goto Next or Prev Trans Unit if (event.getRowType() == null ) { if (step > 0) editor.handleNext(); else editor.handlePrev(); } //If goto Next or Prev Fuzzy/New Trans Unit if (event.getRowType() == ContentState.NeedReview || event.getRowType() == ContentState.New) { if (step > 0) editor.handleNextFuzzy(event.getRowType()); else editor.handlePrevFuzzy(event.getRowType()); } } } })); registerHandler(eventBus.addHandler(TransMemoryCopyEvent.getType(), new TransMemoryCopyHandler() { @Override public void onTransMemoryCopy(TransMemoryCopyEvent event) { // When user clicked on copy-to-target anchor, it checks // if user is editing any target. Notifies if not. if (display.getTargetCellEditor().isEditing()) { display.getTargetCellEditor().setText(event.getTargetResult()); eventBus.fireEvent( new NotificationEvent(Severity.Info, "Message has been copied to the target.")); } else eventBus.fireEvent( new NotificationEvent(Severity.Error, "Please open the target in the editor first.")); } })); display.gotoFirstPage(); } public Integer getRowOffset(TransUnitId transUnitId) { // TODO inefficient! for (int i=0; i<display.getRowValues().size(); i++) { if (transUnitId.equals(display.getTransUnitValue(i).getId())) { Log.info("getRowOffset returning "+i); return i; } } return null; } private final TableModelHandler<TransUnit> tableModelHandler = new TableModelHandler<TransUnit>() { @Override public void requestRows(final Request request, final Callback<TransUnit> callback) { int numRows = request.getNumRows(); int startRow = request.getStartRow(); Log.info("Table requesting" + numRows + " starting from "+ startRow); if(documentId == null){ callback.onFailure(new RuntimeException("No DocumentId")); return; } dispatcher.execute(new GetTransUnits(documentId, workspaceContext.getLocaleId(), startRow, numRows), new AsyncCallback<GetTransUnitsResult>() { @Override public void onSuccess(GetTransUnitsResult result) { SerializableResponse<TransUnit> response = new SerializableResponse<TransUnit>( result.getUnits()); Log.debug("Got " + result.getUnits().size() +" rows back"); callback.onRowsReady(request, response); Log.info("Total of " + result.getTotalCount() + " rows available"); display.getTableModel().setRowCount(result.getTotalCount()); } @Override public void onFailure(Throwable caught) { if(caught instanceof AuthenticationError) { eventBus.fireEvent( new NotificationEvent(Severity.Error, "Not logged in!")); } else if(caught instanceof AuthorizationError) { eventBus.fireEvent( new NotificationEvent(Severity.Error, "Failed to load data from Server")); } else { Log.error("GetTransUnits failure " + caught); eventBus.fireEvent( new NotificationEvent(Severity.Error, "An unknown error occurred")); } } }); } @Override public boolean onSetRowValue(int row, TransUnit rowValue) { dispatcher.execute( new UpdateTransUnit(rowValue.getId(), workspaceContext.getLocaleId(), rowValue.getTarget(),rowValue.getStatus()), new AsyncCallback<UpdateTransUnitResult>() { @Override public void onFailure(Throwable caught) { Log.error("UpdateTransUnit failure " + caught); eventBus.fireEvent(new NotificationEvent(Severity.Error, "Failed to update Translation Unit")); } @Override public void onSuccess(UpdateTransUnitResult result) { eventBus.fireEvent(new NotificationEvent(Severity.Info, "Saved change to Translation Unit")); } }); dispatcher.execute( new EditingTranslationAction(rowValue.getId(), workspaceContext.getLocaleId(), identity.getSessionId(), EditState.StopEditing), new AsyncCallback<EditingTranslationResult>() { @Override public void onFailure(Throwable caught) { eventBus.fireEvent(new NotificationEvent(Severity.Error, "Failed to Stop Editing TransUnit")); } @Override public void onSuccess(EditingTranslationResult result) { //eventBus.fireEvent(new NotificationEvent(Severity.Warning, "TransUnit Editing is finished")); } }); return true; } public void onCancel(TransUnit rowValue) { //stopEditing(rowValue); } @Override public void gotoRow(int row) { selectedTransUnit = display.getTransUnitValue(row); display.gotoRow(row); } @Override public void gotoNextFuzzy(int row, ContentState state) { nextFuzzy(row, state); } @Override public void gotoPrevFuzzy(int row, ContentState state) { prevFuzzy(row, state); } }; private void stopEditing(TransUnit rowValue) { dispatcher.execute( new EditingTranslationAction(rowValue.getId(), workspaceContext.getLocaleId(), identity.getSessionId(), EditState.StopEditing), new AsyncCallback<EditingTranslationResult>() { @Override public void onSuccess(EditingTranslationResult result) { //eventBus.fireEvent(new NotificationEvent(Severity.Warning, "TransUnit Editing is finished")); } @Override public void onFailure(Throwable caught) { eventBus.fireEvent(new NotificationEvent(Severity.Error, "Failed to Stop Editing TransUnit")); } }); } private void startEditing(TransUnit rowValue) { //Send a START_EDIT event dispatcher.execute( new EditingTranslationAction( rowValue.getId(), workspaceContext.getLocaleId(), identity.getSessionId(), EditState.StartEditing), new AsyncCallback<EditingTranslationResult>() { @Override public void onFailure(Throwable caught) { eventBus.fireEvent(new NotificationEvent(Severity.Error, "Failed to Lock TransUnit")); } @Override public void onSuccess(EditingTranslationResult result) { } }); } private void prevFuzzy(int row, ContentState desiredState) { int currow = row; row=row-1; while(row > 0) { if(display.getTransUnitValue(row).getStatus() == desiredState) { display.gotoRow(row); selectedTransUnit = display.getTransUnitValue(row); break; } else { row = row - 1; } } //If the last row is not fuzzy, we will keep the editor in current row open if(row == 0 && display.getTransUnitValue(row).getStatus() != desiredState) { display.gotoRow(currow); selectedTransUnit = display.getTransUnitValue(currow); } else if(row == 0 && display.getTransUnitValue(row).getStatus() == desiredState) { display.gotoRow(row); selectedTransUnit = display.getTransUnitValue(row); } } private void nextFuzzy(int row, ContentState desiredState) { int currow = row; row=row+1; while(row < MAX_PAGE_ROW) { if(display.getTransUnitValue(row).getStatus()==desiredState) { selectedTransUnit = display.getTransUnitValue(row); display.gotoRow(row); break; } else { row = row + 1; } } //If the last row is not fuzzy, we will keep the editor in current row open if(row == MAX_PAGE_ROW && display.getTransUnitValue(row).getStatus() !=desiredState) { display.gotoRow(currow); selectedTransUnit = display.getTransUnitValue(currow); } else if(row == MAX_PAGE_ROW && display.getTransUnitValue(row).getStatus() ==desiredState) { display.gotoRow(row); selectedTransUnit = display.getTransUnitValue(row); } } public TransUnit getSelectedTransUnit() { return selectedTransUnit; } @Override protected void onPlaceRequest(PlaceRequest request) { } @Override protected void onUnbind() { } @Override public void refreshDisplay() { } @Override public void revealDisplay() { } @Override public void gotoFirstPage() { display.gotoFirstPage(); } @Override public void gotoLastPage() { display.gotoLastPage(); } @Override public void gotoNextPage() { display.gotoNextPage(); } @Override public void gotoPage(int page, boolean forced) { display.gotoPage(page, forced); } @Override public void gotoPreviousPage() { display.gotoPreviousPage(); } @Override public HandlerRegistration addPageChangeHandler(PageChangeHandler handler) { return display.getPageChangeHandlers().addPageChangeHandler(handler); } @Override public HandlerRegistration addPageCountChangeHandler( PageCountChangeHandler handler) { return display.getPageCountChangeHandlers().addPageCountChangeHandler(handler); } public DocumentId getDocumentId() { return documentId; } }
flies-war/src/main/java/org/fedorahosted/flies/webtrans/editor/table/TableEditorPresenter.java
package org.fedorahosted.flies.webtrans.editor.table; import static org.fedorahosted.flies.webtrans.editor.table.TableConstants.MAX_PAGE_ROW; import java.util.List; import net.customware.gwt.dispatch.client.DispatchAsync; import net.customware.gwt.presenter.client.EventBus; import net.customware.gwt.presenter.client.place.Place; import net.customware.gwt.presenter.client.place.PlaceRequest; import net.customware.gwt.presenter.client.widget.WidgetDisplay; import org.fedorahosted.flies.common.ContentState; import org.fedorahosted.flies.common.EditState; import org.fedorahosted.flies.gwt.auth.AuthenticationError; import org.fedorahosted.flies.gwt.auth.AuthorizationError; import org.fedorahosted.flies.gwt.model.DocumentId; import org.fedorahosted.flies.gwt.model.TransUnit; import org.fedorahosted.flies.gwt.model.TransUnitId; import org.fedorahosted.flies.gwt.rpc.EditingTranslationAction; import org.fedorahosted.flies.gwt.rpc.EditingTranslationResult; import org.fedorahosted.flies.gwt.rpc.GetTransUnits; import org.fedorahosted.flies.gwt.rpc.GetTransUnitsResult; import org.fedorahosted.flies.gwt.rpc.UpdateTransUnit; import org.fedorahosted.flies.gwt.rpc.UpdateTransUnitResult; import org.fedorahosted.flies.webtrans.client.DocumentSelectionEvent; import org.fedorahosted.flies.webtrans.client.DocumentSelectionHandler; import org.fedorahosted.flies.webtrans.client.NavTransUnitEvent; import org.fedorahosted.flies.webtrans.client.NavTransUnitHandler; import org.fedorahosted.flies.webtrans.client.NotificationEvent; import org.fedorahosted.flies.webtrans.client.TransMemoryCopyEvent; import org.fedorahosted.flies.webtrans.client.TransMemoryCopyHandler; import org.fedorahosted.flies.webtrans.client.WorkspaceContext; import org.fedorahosted.flies.webtrans.client.NotificationEvent.Severity; import org.fedorahosted.flies.webtrans.client.auth.Identity; import org.fedorahosted.flies.webtrans.client.events.TransUnitEditEvent; import org.fedorahosted.flies.webtrans.client.events.TransUnitEditEventHandler; import org.fedorahosted.flies.webtrans.client.events.TransUnitUpdatedEvent; import org.fedorahosted.flies.webtrans.client.events.TransUnitUpdatedEventHandler; import org.fedorahosted.flies.webtrans.client.rpc.CachingDispatchAsync; import org.fedorahosted.flies.webtrans.editor.DocumentEditorPresenter; import org.fedorahosted.flies.webtrans.editor.HasPageNavigation; import org.fedorahosted.flies.webtrans.editor.filter.ContentFilter; import org.fedorahosted.flies.webtrans.editor.filter.FilterDisabledEvent; import org.fedorahosted.flies.webtrans.editor.filter.FilterDisabledEventHandler; import org.fedorahosted.flies.webtrans.editor.filter.FilterEnabledEvent; import org.fedorahosted.flies.webtrans.editor.filter.FilterEnabledEventHandler; import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.event.logical.shared.HasSelectionHandlers; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.gen2.event.shared.HandlerRegistration; import com.google.gwt.gen2.table.client.TableModel; import com.google.gwt.gen2.table.client.TableModel.Callback; import com.google.gwt.gen2.table.client.TableModelHelper.Request; import com.google.gwt.gen2.table.client.TableModelHelper.SerializableResponse; import com.google.gwt.gen2.table.event.client.HasPageChangeHandlers; import com.google.gwt.gen2.table.event.client.HasPageCountChangeHandlers; import com.google.gwt.gen2.table.event.client.PageChangeHandler; import com.google.gwt.gen2.table.event.client.PageCountChangeHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.inject.Inject; public class TableEditorPresenter extends DocumentEditorPresenter<TableEditorPresenter.Display> implements HasPageNavigation, HasPageChangeHandlers, HasPageCountChangeHandlers { public static final Place PLACE = new Place("TableEditor"); public interface Display extends WidgetDisplay, HasPageNavigation { HasSelectionHandlers<TransUnit> getSelectionHandlers(); HasPageChangeHandlers getPageChangeHandlers(); HasPageCountChangeHandlers getPageCountChangeHandlers(); RedirectingCachedTableModel<TransUnit> getTableModel(); void setTableModelHandler(TableModelHandler<TransUnit> hadler); void reloadPage(); void setPageSize(int size); void setContentFilter(ContentFilter<TransUnit> filter); void clearContentFilter(); void gotoRow(int row); int getCurrentPageNumber(); TransUnit getTransUnitValue(int row); InlineTargetCellEditor getTargetCellEditor(); List<TransUnit> getRowValues(); int getCurrentPage(); int getPageSize(); } private DocumentId documentId; private final DispatchAsync dispatcher; private final WorkspaceContext workspaceContext; private final Identity identity; @Inject public TableEditorPresenter(final Display display, final EventBus eventBus, final CachingDispatchAsync dispatcher,final Identity identity, final WorkspaceContext workspaceContext) { super(display, eventBus); this.dispatcher = dispatcher; this.workspaceContext = workspaceContext; this.identity = identity; } @Override public Place getPlace() { return PLACE; } private TransUnit selectedTransUnit; @Override protected void onBind() { display.setTableModelHandler(tableModelHandler); display.setPageSize(TableConstants.PAGE_SIZE); registerHandler(display.getSelectionHandlers().addSelectionHandler(new SelectionHandler<TransUnit>() { @Override public void onSelection(SelectionEvent<TransUnit> event) { if(event.getSelectedItem() != selectedTransUnit) { selectedTransUnit = event.getSelectedItem(); //startEditing(selectedTransUnit); eventBus.fireEvent(event); } } })); registerHandler( eventBus.addHandler(DocumentSelectionEvent.getType(), new DocumentSelectionHandler() { @Override public void onDocumentSelected(DocumentSelectionEvent event) { if(!event.getDocumentId().equals(documentId)) { documentId = event.getDocumentId(); display.getTableModel().clearCache(); display.getTableModel().setRowCount(TableModel.UNKNOWN_ROW_COUNT); display.gotoPage(0, true); } } }) ); registerHandler(eventBus.addHandler(FilterEnabledEvent.getType(), new FilterEnabledEventHandler() { @Override public void onFilterEnabled(FilterEnabledEvent event) { display.setContentFilter(event.getContentFilter()); } })); registerHandler(eventBus.addHandler(FilterDisabledEvent.getType(), new FilterDisabledEventHandler() { @Override public void onFilterDisabled(FilterDisabledEvent event) { display.clearContentFilter(); } })); registerHandler(eventBus.addHandler(TransUnitUpdatedEvent.getType(), new TransUnitUpdatedEventHandler() { @Override public void onTransUnitUpdated(TransUnitUpdatedEvent event) { if(documentId != null && documentId.equals(event.getDocumentId())) { if(selectedTransUnit != null && selectedTransUnit.getId().equals(event.getTransUnitId())) { // handle change in current selection //eventBus.fireEvent(new NotificationEvent(Severity.Warning, "Someone else updated this translation unit. you're in trouble...")); //display.getTableModel().setRowValue(row, rowValue); } boolean reloadPage = false; if (reloadPage) { display.getTableModel().clearCache(); display.reloadPage(); } else { final Integer rowOffset = getRowOffset(event.getTransUnitId()); // - add TU index to model if (rowOffset != null) { final int row = display.getCurrentPage() * display.getPageSize() + rowOffset; dispatcher.execute(new GetTransUnits( documentId, workspaceContext.getLocaleId(), row, 1), new AsyncCallback<GetTransUnitsResult>() { @Override public void onFailure(Throwable e) { Log.error(e.getMessage(), e); } @Override public void onSuccess(GetTransUnitsResult result) { display.getTableModel().setRowValueOverride(row, result.getUnits().get(0)); } }); } else { display.getTableModel().clearCache(); } } } } })); registerHandler(eventBus.addHandler(TransUnitEditEvent.getType(), new TransUnitEditEventHandler() { @Override public void onTransUnitEdit(TransUnitEditEvent event) { if(documentId != null && documentId.equals(event.getDocumentId())) { if(selectedTransUnit != null && selectedTransUnit.getId().equals(event.getTransUnitId())) { // handle change in current selection if(!event.getSessionId().equals(identity.getSessionId())) eventBus.fireEvent(new NotificationEvent(Severity.Warning, "Warning: This Translation Unit is being edited by someone else.")); } //display.getTableModel().clearCache(); //display.reloadPage(); } } })); registerHandler(eventBus.addHandler(NavTransUnitEvent.getType(), new NavTransUnitHandler() { @Override public void onNavTransUnit(NavTransUnitEvent event) { if(selectedTransUnit != null) { int step = event.getStep(); //Send message to server to stop editing current selection //stopEditing(selectedTransUnit); InlineTargetCellEditor editor = display.getTargetCellEditor(); //If goto Next or Prev Trans Unit if (event.getRowType() == null ) { if (step > 0) editor.handleNext(); else editor.handlePrev(); } //If goto Next or Prev Fuzzy/New Trans Unit if (event.getRowType() == ContentState.NeedReview || event.getRowType() == ContentState.New) { if (step > 0) editor.handleNextFuzzy(event.getRowType()); else editor.handlePrevFuzzy(event.getRowType()); } } } })); registerHandler(eventBus.addHandler(TransMemoryCopyEvent.getType(), new TransMemoryCopyHandler() { @Override public void onTransMemoryCopy(TransMemoryCopyEvent event) { // When user clicked on copy-to-target anchor, it checks // if user is editing any target. Notifies if not. if (display.getTargetCellEditor().isEditing()) { display.getTargetCellEditor().setText(event.getTargetResult()); eventBus.fireEvent( new NotificationEvent(Severity.Info, "Message has been copied to the target.")); } else eventBus.fireEvent( new NotificationEvent(Severity.Error, "Please open the target in the editor first.")); } })); display.gotoFirstPage(); } public Integer getRowOffset(TransUnitId transUnitId) { // TODO inefficient! for (int i=0; i<display.getRowValues().size(); i++) { if (transUnitId.equals(display.getTransUnitValue(i).getId())) { return i; } } return null; } private final TableModelHandler<TransUnit> tableModelHandler = new TableModelHandler<TransUnit>() { @Override public void requestRows(final Request request, final Callback<TransUnit> callback) { int numRows = request.getNumRows(); int startRow = request.getStartRow(); Log.info("Table requesting" + numRows + " starting from "+ startRow); if(documentId == null){ callback.onFailure(new RuntimeException("No DocumentId")); return; } dispatcher.execute(new GetTransUnits(documentId, workspaceContext.getLocaleId(), startRow, numRows), new AsyncCallback<GetTransUnitsResult>() { @Override public void onSuccess(GetTransUnitsResult result) { SerializableResponse<TransUnit> response = new SerializableResponse<TransUnit>( result.getUnits()); Log.debug("Got " + result.getUnits().size() +" rows back"); callback.onRowsReady(request, response); Log.info("Total of " + result.getTotalCount() + " rows available"); display.getTableModel().setRowCount(result.getTotalCount()); } @Override public void onFailure(Throwable caught) { if(caught instanceof AuthenticationError) { eventBus.fireEvent( new NotificationEvent(Severity.Error, "Not logged in!")); } else if(caught instanceof AuthorizationError) { eventBus.fireEvent( new NotificationEvent(Severity.Error, "Failed to load data from Server")); } else { Log.error("GetTransUnits failure " + caught); eventBus.fireEvent( new NotificationEvent(Severity.Error, "An unknown error occurred")); } } }); } @Override public boolean onSetRowValue(int row, TransUnit rowValue) { dispatcher.execute( new UpdateTransUnit(rowValue.getId(), workspaceContext.getLocaleId(), rowValue.getTarget(),rowValue.getStatus()), new AsyncCallback<UpdateTransUnitResult>() { @Override public void onFailure(Throwable caught) { Log.error("UpdateTransUnit failure " + caught); eventBus.fireEvent(new NotificationEvent(Severity.Error, "Failed to update Translation Unit")); } @Override public void onSuccess(UpdateTransUnitResult result) { eventBus.fireEvent(new NotificationEvent(Severity.Info, "Saved change to Translation Unit")); } }); dispatcher.execute( new EditingTranslationAction(rowValue.getId(), workspaceContext.getLocaleId(), identity.getSessionId(), EditState.StopEditing), new AsyncCallback<EditingTranslationResult>() { @Override public void onFailure(Throwable caught) { eventBus.fireEvent(new NotificationEvent(Severity.Error, "Failed to Stop Editing TransUnit")); } @Override public void onSuccess(EditingTranslationResult result) { //eventBus.fireEvent(new NotificationEvent(Severity.Warning, "TransUnit Editing is finished")); } }); return true; } public void onCancel(TransUnit rowValue) { //stopEditing(rowValue); } @Override public void gotoRow(int row) { selectedTransUnit = display.getTransUnitValue(row); display.gotoRow(row); } @Override public void gotoNextFuzzy(int row, ContentState state) { nextFuzzy(row, state); } @Override public void gotoPrevFuzzy(int row, ContentState state) { prevFuzzy(row, state); } }; private void stopEditing(TransUnit rowValue) { dispatcher.execute( new EditingTranslationAction(rowValue.getId(), workspaceContext.getLocaleId(), identity.getSessionId(), EditState.StopEditing), new AsyncCallback<EditingTranslationResult>() { @Override public void onSuccess(EditingTranslationResult result) { //eventBus.fireEvent(new NotificationEvent(Severity.Warning, "TransUnit Editing is finished")); } @Override public void onFailure(Throwable caught) { eventBus.fireEvent(new NotificationEvent(Severity.Error, "Failed to Stop Editing TransUnit")); } }); } private void startEditing(TransUnit rowValue) { //Send a START_EDIT event dispatcher.execute( new EditingTranslationAction( rowValue.getId(), workspaceContext.getLocaleId(), identity.getSessionId(), EditState.StartEditing), new AsyncCallback<EditingTranslationResult>() { @Override public void onFailure(Throwable caught) { eventBus.fireEvent(new NotificationEvent(Severity.Error, "Failed to Lock TransUnit")); } @Override public void onSuccess(EditingTranslationResult result) { } }); } private void prevFuzzy(int row, ContentState desiredState) { int currow = row; row=row-1; while(row > 0) { if(display.getTransUnitValue(row).getStatus() == desiredState) { display.gotoRow(row); selectedTransUnit = display.getTransUnitValue(row); break; } else { row = row - 1; } } //If the last row is not fuzzy, we will keep the editor in current row open if(row == 0 && display.getTransUnitValue(row).getStatus() != desiredState) { display.gotoRow(currow); selectedTransUnit = display.getTransUnitValue(currow); } else if(row == 0 && display.getTransUnitValue(row).getStatus() == desiredState) { display.gotoRow(row); selectedTransUnit = display.getTransUnitValue(row); } } private void nextFuzzy(int row, ContentState desiredState) { int currow = row; row=row+1; while(row < MAX_PAGE_ROW) { if(display.getTransUnitValue(row).getStatus()==desiredState) { selectedTransUnit = display.getTransUnitValue(row); display.gotoRow(row); break; } else { row = row + 1; } } //If the last row is not fuzzy, we will keep the editor in current row open if(row == MAX_PAGE_ROW && display.getTransUnitValue(row).getStatus() !=desiredState) { display.gotoRow(currow); selectedTransUnit = display.getTransUnitValue(currow); } else if(row == MAX_PAGE_ROW && display.getTransUnitValue(row).getStatus() ==desiredState) { display.gotoRow(row); selectedTransUnit = display.getTransUnitValue(row); } } public TransUnit getSelectedTransUnit() { return selectedTransUnit; } @Override protected void onPlaceRequest(PlaceRequest request) { } @Override protected void onUnbind() { } @Override public void refreshDisplay() { } @Override public void revealDisplay() { } @Override public void gotoFirstPage() { display.gotoFirstPage(); } @Override public void gotoLastPage() { display.gotoLastPage(); } @Override public void gotoNextPage() { display.gotoNextPage(); } @Override public void gotoPage(int page, boolean forced) { display.gotoPage(page, forced); } @Override public void gotoPreviousPage() { display.gotoPreviousPage(); } @Override public HandlerRegistration addPageChangeHandler(PageChangeHandler handler) { return display.getPageChangeHandlers().addPageChangeHandler(handler); } @Override public HandlerRegistration addPageCountChangeHandler( PageCountChangeHandler handler) { return display.getPageCountChangeHandlers().addPageCountChangeHandler(handler); } public DocumentId getDocumentId() { return documentId; } }
Disabled updates for individual rows
flies-war/src/main/java/org/fedorahosted/flies/webtrans/editor/table/TableEditorPresenter.java
Disabled updates for individual rows
Java
lgpl-2.1
e098b108f0b1dbc9ed75fff571dfa9a9b5556b3b
0
ironjacamar/ironjacamar,jandsu/ironjacamar,ironjacamar/ironjacamar,darranl/ironjacamar,rarguello/ironjacamar,ironjacamar/ironjacamar,johnaoahra80/ironjacamar,maeste/ironjacamar,jesperpedersen/ironjacamar,jpkrohling/ironjacamar
/* * JBoss, Home of Professional Open Source. * Copyright 2008-2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jca.sjc.deployers.ra; import org.jboss.jca.sjc.deployers.Deployer; import org.jboss.jca.sjc.deployers.Deployment; import java.io.File; import java.net.URL; import org.jboss.logging.Logger; import org.jboss.metadata.rar.jboss.JBossRAMetaData; import org.jboss.metadata.rar.spec.ConnectorMetaData; import org.jboss.metadata.rar.spec.JCA15MetaData; import org.jboss.metadata.rar.spec.JCA16MetaData; import org.jboss.xb.binding.Unmarshaller; import org.jboss.xb.binding.UnmarshallerFactory; import org.jboss.xb.binding.resolver.MutableSchemaResolver; import org.jboss.xb.binding.sunday.unmarshalling.SingletonSchemaResolverFactory; /** * The RA deployer for JCA/SJC * @author <a href="mailto:jesper.pedersen@jboss.org">Jesper Pedersen</a> */ public class RADeployer implements Deployer { private static Logger log = Logger.getLogger(RADeployer.class); private static boolean trace = log.isTraceEnabled(); /** * Constructor */ public RADeployer() { } /** * Deploy * @param f The file * @param parent The parent classloader * @return The deployment * @exception Exception Thrown if an error occurs */ public Deployment deploy(File f, ClassLoader parent) throws Exception { if (f == null || !f.getAbsolutePath().endsWith(".rar")) return null; log.info("Deploying: " + f.getAbsolutePath()); File root = null; if (f.isFile()) { File destination = new File(SecurityActions.getSystemProperty("jboss.jca.home"), "/tmp/"); root = ExtractUtil.extract(f, destination); } else { root = f; } ConnectorMetaData cmd = getStandardMetaData(root); JBossRAMetaData jrmd = getJBossMetaData(root); return null; } /** * Get the JCA standard metadata * @param root The root of the deployment * @return The metadata * @exception Exception Thrown if an error occurs */ private ConnectorMetaData getStandardMetaData(File root) throws Exception { ConnectorMetaData result = null; UnmarshallerFactory unmarshallerFactory = UnmarshallerFactory.newInstance(); Unmarshaller unmarshaller = unmarshallerFactory.newUnmarshaller(); MutableSchemaResolver resolver = SingletonSchemaResolverFactory.getInstance().getSchemaBindingResolver(); resolver.mapLocationToClass("http://java.sun.com/xml/ns/j2ee/connector_1_6.xsd", JCA16MetaData.class); resolver.mapLocationToClass("http://java.sun.com/xml/ns/j2ee/connector_1_5.xsd", JCA15MetaData.class); File metadataFile = new File(root, "/META-INF/ra.xml"); if (metadataFile.exists()) { String url = metadataFile.getAbsolutePath(); try { long start = System.currentTimeMillis(); result = (ConnectorMetaData)unmarshaller.unmarshal(url, resolver); log.debug("Total parse for " + url + " took " + (System.currentTimeMillis() - start) + "ms"); if (trace) log.trace(result); } catch (Exception e) { log.error("Error during parsing: " + url, e); throw e; } } return result; } /** * Get the JBoss specific metadata * @param root The root of the deployment * @return The metadata * @exception Exception Thrown if an error occurs */ private JBossRAMetaData getJBossMetaData(File root) throws Exception { JBossRAMetaData result = null; UnmarshallerFactory unmarshallerFactory = UnmarshallerFactory.newInstance(); Unmarshaller unmarshaller = unmarshallerFactory.newUnmarshaller(); MutableSchemaResolver resolver = SingletonSchemaResolverFactory.getInstance().getSchemaBindingResolver(); resolver.mapLocationToClass("http://www.jboss.org/schema/jboss-ra_1_0.xsd", JBossRAMetaData.class); File metadataFile = new File(root, "/META-INF/jboss-ra.xml"); if (metadataFile.exists()) { String url = metadataFile.getAbsolutePath(); try { long start = System.currentTimeMillis(); result = (JBossRAMetaData)unmarshaller.unmarshal(url, resolver); log.debug("Total parse for " + url + " took " + (System.currentTimeMillis() - start) + "ms"); if (trace) log.trace(result); } catch (Exception e) { log.error("Error during parsing: " + url, e); throw e; } } return result; } }
sjc/src/main/java/org/jboss/jca/sjc/deployers/ra/RADeployer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008-2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jca.sjc.deployers.ra; import org.jboss.jca.sjc.deployers.Deployer; import org.jboss.jca.sjc.deployers.Deployment; import java.io.File; import java.net.URL; import org.jboss.logging.Logger; import org.jboss.metadata.rar.jboss.JBossRAMetaData; import org.jboss.metadata.rar.spec.ConnectorMetaData; import org.jboss.metadata.rar.spec.JCA15MetaData; import org.jboss.metadata.rar.spec.JCA16MetaData; import org.jboss.xb.binding.Unmarshaller; import org.jboss.xb.binding.UnmarshallerFactory; import org.jboss.xb.binding.resolver.MultiClassSchemaResolver; import org.jboss.xb.binding.resolver.MutableSchemaResolver; import org.jboss.xb.binding.sunday.unmarshalling.SingletonSchemaResolverFactory; /** * The RA deployer for JCA/SJC * @author <a href="mailto:jesper.pedersen@jboss.org">Jesper Pedersen</a> */ public class RADeployer implements Deployer { private static Logger log = Logger.getLogger(RADeployer.class); /** * Constructor */ public RADeployer() { } /** * Deploy * @param f The file * @param parent The parent classloader * @return The deployment * @exception Exception Thrown if an error occurs */ public Deployment deploy(File f, ClassLoader parent) throws Exception { if (f == null || !f.getAbsolutePath().endsWith(".rar")) return null; log.info("Deploying: " + f.getAbsolutePath()); File root = null; if (f.isFile()) { File destination = new File(SecurityActions.getSystemProperty("jboss.jca.home"), "/tmp/"); root = ExtractUtil.extract(f, destination); } else { root = f; } ConnectorMetaData cmd = getStandardMetaData(root); JBossRAMetaData jrmd = getJBossMetaData(root); return null; } /** * Get the JCA standard metadata * @param root The root of the deployment * @return The metadata * @exception Exception Thrown if an error occurs */ private ConnectorMetaData getStandardMetaData(File root) throws Exception { ConnectorMetaData result = null; UnmarshallerFactory unmarshallerFactory = UnmarshallerFactory.newInstance(); Unmarshaller unmarshaller = unmarshallerFactory.newUnmarshaller(); MutableSchemaResolver resolver = SingletonSchemaResolverFactory.getInstance().getSchemaBindingResolver(); resolver.mapLocationToClass("http://java.sun.com/xml/ns/j2ee/connector_1_6.xsd", JCA16MetaData.class); resolver.mapLocationToClass("http://java.sun.com/xml/ns/j2ee/connector_1_5.xsd", JCA15MetaData.class); File metadataFile = new File(root, "/META-INF/ra.xml"); if (metadataFile.exists()) { String url = metadataFile.getAbsolutePath(); try { long start = System.currentTimeMillis(); result = (ConnectorMetaData)unmarshaller.unmarshal(url, resolver); log.debug("Total parse for " + url + " took " + (System.currentTimeMillis() - start) + "ms"); log.info(result); } catch (Exception e) { log.error("Error during parsing: " + url, e); throw e; } } return result; } /** * Get the JBoss specific metadata * @param root The root of the deployment * @return The metadata * @exception Exception Thrown if an error occurs */ private JBossRAMetaData getJBossMetaData(File root) throws Exception { JBossRAMetaData result = null; UnmarshallerFactory unmarshallerFactory = UnmarshallerFactory.newInstance(); Unmarshaller unmarshaller = unmarshallerFactory.newUnmarshaller(); MutableSchemaResolver resolver = SingletonSchemaResolverFactory.getInstance().getSchemaBindingResolver(); resolver.mapLocationToClass("http://www.jboss.org/schema/jboss-ra_1_0.xsd", JBossRAMetaData.class); File metadataFile = new File(root, "/META-INF/jboss-ra.xml"); if (metadataFile.exists()) { String url = metadataFile.getAbsolutePath(); try { long start = System.currentTimeMillis(); result = (JBossRAMetaData)unmarshaller.unmarshal(url, resolver); log.debug("Total parse for " + url + " took " + (System.currentTimeMillis() - start) + "ms"); } catch (Exception e) { log.error("Error during parsing: " + url, e); throw e; } } return result; } }
fix logging levels
sjc/src/main/java/org/jboss/jca/sjc/deployers/ra/RADeployer.java
fix logging levels
Java
apache-2.0
ed8a59cd62c8a873655f6ef2a6e094a64cdf075c
0
kubernetes-client/java,kubernetes-client/java
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.kubernetes.client.informer; import com.google.gson.reflect.TypeToken; import io.kubernetes.client.common.KubernetesListObject; import io.kubernetes.client.common.KubernetesObject; import io.kubernetes.client.informer.impl.DefaultSharedIndexInformer; import io.kubernetes.client.openapi.ApiClient; import io.kubernetes.client.openapi.ApiException; import io.kubernetes.client.openapi.Configuration; import io.kubernetes.client.util.CallGenerator; import io.kubernetes.client.util.CallGeneratorParams; import io.kubernetes.client.util.Namespaces; import io.kubernetes.client.util.Watch; import io.kubernetes.client.util.Watchable; import io.kubernetes.client.util.generic.GenericKubernetesApi; import io.kubernetes.client.util.generic.options.ListOptions; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import okhttp3.Call; import org.apache.commons.collections4.MapUtils; /** SharedInformerFactory class constructs and caches informers for api types. */ public class SharedInformerFactory { protected Map<Type, SharedIndexInformer> informers; private Map<Type, Future> startedInformers; private ExecutorService informerExecutor; private ApiClient apiClient; /** Constructor w/ default thread pool. */ public SharedInformerFactory() { this(Configuration.getDefaultApiClient().setReadTimeout(0), Executors.newCachedThreadPool()); } /** Constructor w/ api client specified and default thread pool. */ public SharedInformerFactory(ApiClient apiClient) { this(apiClient, Executors.newCachedThreadPool()); } /** * Constructor w/ thread pool specified. * * @param threadPool specified thread pool */ public SharedInformerFactory(ExecutorService threadPool) { this(Configuration.getDefaultApiClient().setReadTimeout(0), threadPool); } /** * Constructor w/ api client and thread pool specified. * * @param client specific api client * @param threadPool specified thread pool */ public SharedInformerFactory(ApiClient client, ExecutorService threadPool) { if (client.getReadTimeout() != 0) { throw new IllegalArgumentException("read timeout of ApiClient must be zero"); } apiClient = client; informerExecutor = threadPool; informers = new HashMap<>(); startedInformers = new HashMap<>(); } /** * Shared index informer for shared index informer. * * @param <ApiType> the type parameter * @param <ApiListType> the type parameter * @param callGenerator the call generator * @param apiTypeClass the api type class * @param apiListTypeClass the api list type class * @return the shared index informer */ public synchronized <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> SharedIndexInformer<ApiType> sharedIndexInformerFor( CallGenerator callGenerator, Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass) { return sharedIndexInformerFor(callGenerator, apiTypeClass, apiListTypeClass, 0); } /** * Constructs and returns a shared index informer w/ resync period specified. But the informer * cache will not be overwritten i.e. only the first registered informer will be kept. * * @param <ApiType> the type parameter * @param <ApiListType> the type parameter * @param callGenerator the call generator * @param apiTypeClass the api type class * @param apiListTypeClass the api list type class * @param resyncPeriodInMillis the resync period in millis * @return the shared index informer */ public synchronized <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> SharedIndexInformer<ApiType> sharedIndexInformerFor( CallGenerator callGenerator, Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass, long resyncPeriodInMillis) { ListerWatcher<ApiType, ApiListType> listerWatcher = listerWatcherFor(callGenerator, apiTypeClass, apiListTypeClass); return sharedIndexInformerFor(listerWatcher, apiTypeClass, resyncPeriodInMillis); } /** * Constructs and returns a shared index informer by specifying lister-watcher. But the informer * cache will not be overwritten on multiple call w/ the the same apiTypeClass i.e. only the first * registered informer will be kept. * * @param <ApiType> the type parameter * @param <ApiListType> the type parameter * @param listerWatcher the lister watcher * @param apiTypeClass the api type class * @param resyncPeriodInMillis the resync period in millis * @return the shared index informer */ public synchronized <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> SharedIndexInformer<ApiType> sharedIndexInformerFor( ListerWatcher<ApiType, ApiListType> listerWatcher, Class<ApiType> apiTypeClass, long resyncPeriodInMillis) { SharedIndexInformer<ApiType> informer = new DefaultSharedIndexInformer<>(apiTypeClass, listerWatcher, resyncPeriodInMillis); this.informers.putIfAbsent(TypeToken.get(apiTypeClass).getType(), informer); return informer; } /** * Constructs and returns a shared index informer by specifying a generic api instance. But the * informer cache will not be overwritten on multiple call w/ the the same apiTypeClass i.e. only * the first registered informer will be kept. * * @param <ApiType> the type parameter * @param <ApiListType> the type parameter * @param genericKubernetesApi the generic kubernetes api * @param apiTypeClass the api type class * @param resyncPeriodInMillis the resync period in millis * @return the shared index informer */ public synchronized <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> SharedIndexInformer<ApiType> sharedIndexInformerFor( GenericKubernetesApi<ApiType, ApiListType> genericKubernetesApi, Class<ApiType> apiTypeClass, long resyncPeriodInMillis) { return sharedIndexInformerFor( genericKubernetesApi, apiTypeClass, resyncPeriodInMillis, Namespaces.NAMESPACE_ALL); } /** * Working the same as {@link SharedInformerFactory#sharedIndexInformerFor} above. * * <p>Constructs and returns a shared index informer for a specific namespace. * * @param <ApiType> the type parameter * @param <ApiListType> the type parameter * @param genericKubernetesApi the generic kubernetes api * @param apiTypeClass the api type class * @param resyncPeriodInMillis the resync period in millis * @param namespace the target namespace * @return the shared index informer */ public synchronized <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> SharedIndexInformer<ApiType> sharedIndexInformerFor( GenericKubernetesApi<ApiType, ApiListType> genericKubernetesApi, Class<ApiType> apiTypeClass, long resyncPeriodInMillis, String namespace) { ListerWatcher<ApiType, ApiListType> listerWatcher = listerWatcherFor(genericKubernetesApi, namespace); return sharedIndexInformerFor(listerWatcher, apiTypeClass, resyncPeriodInMillis); } private <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> ListerWatcher<ApiType, ApiListType> listerWatcherFor( CallGenerator callGenerator, Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass) { if (apiClient.getReadTimeout() > 0) { // set read timeout zero to ensure client doesn't time out apiClient.setReadTimeout(0); } return new ListerWatcher<ApiType, ApiListType>() { @Override public ApiListType list(CallGeneratorParams params) throws ApiException { Call call = callGenerator.generate(params); return (ApiListType) apiClient.execute(call, apiListTypeClass).getData(); } @Override public Watch<ApiType> watch(CallGeneratorParams params) throws ApiException { Call call = callGenerator.generate(params); // bind call with private http client to make sure read timeout is zero. call = apiClient.getHttpClient().newCall(call.request()); return Watch.createWatch( apiClient, call, TypeToken.getParameterized(Watch.Response.class, apiTypeClass).getType()); } }; } private <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> ListerWatcher<ApiType, ApiListType> listerWatcherFor( GenericKubernetesApi<ApiType, ApiListType> genericKubernetesApi, String namespace) { if (apiClient.getReadTimeout() > 0) { // set read timeout zero to ensure client doesn't time out apiClient.setReadTimeout(0); } // TODO: it seems read timeout is determined by genericKubernetesApi instead of above apiClient. return new ListerWatcher<ApiType, ApiListType>() { public ApiListType list(CallGeneratorParams params) throws ApiException { if (Namespaces.NAMESPACE_ALL.equals(namespace)) { return genericKubernetesApi .list( new ListOptions() { { setResourceVersion(params.resourceVersion); setTimeoutSeconds(params.timeoutSeconds); } }) .throwsApiException() .getObject(); } else { return genericKubernetesApi .list( namespace, new ListOptions() { { setResourceVersion(params.resourceVersion); setTimeoutSeconds(params.timeoutSeconds); } }) .throwsApiException() .getObject(); } } public Watchable<ApiType> watch(CallGeneratorParams params) throws ApiException { if (Namespaces.NAMESPACE_ALL.equals(namespace)) { return genericKubernetesApi.watch(); } else { return genericKubernetesApi.watch(namespace); } } }; } /** * Gets existing shared index informer, return null if the requesting informer is never * constructed. * * @param <ApiType> the type parameter * @param apiTypeClass the api type class * @return the existing shared index informer */ public synchronized <ApiType extends KubernetesObject> SharedIndexInformer<ApiType> getExistingSharedIndexInformer(Class<ApiType> apiTypeClass) { return this.informers.get(TypeToken.get(apiTypeClass).getType()); } /** Start all registered informers. */ public synchronized void startAllRegisteredInformers() { if (MapUtils.isEmpty(informers)) { return; } informers.forEach( (informerType, informer) -> startedInformers.computeIfAbsent( informerType, key -> informerExecutor.submit((Runnable) informer::run))); } /** Stop all registered informers and shut down the thread pool. */ public synchronized void stopAllRegisteredInformers() { stopAllRegisteredInformers(true); } /** * Stop all registered informers. * * @param shutdownThreadPool whether or not to shut down the thread pool. */ public synchronized void stopAllRegisteredInformers(boolean shutdownThreadPool) { if (MapUtils.isEmpty(informers)) { return; } informers.forEach( (informerType, informer) -> { if (startedInformers.remove(informerType) != null) { informer.stop(); } }); if (shutdownThreadPool) { informerExecutor.shutdown(); } } }
util/src/main/java/io/kubernetes/client/informer/SharedInformerFactory.java
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.kubernetes.client.informer; import com.google.gson.reflect.TypeToken; import io.kubernetes.client.common.KubernetesListObject; import io.kubernetes.client.common.KubernetesObject; import io.kubernetes.client.informer.impl.DefaultSharedIndexInformer; import io.kubernetes.client.openapi.ApiClient; import io.kubernetes.client.openapi.ApiException; import io.kubernetes.client.openapi.Configuration; import io.kubernetes.client.util.CallGenerator; import io.kubernetes.client.util.CallGeneratorParams; import io.kubernetes.client.util.Namespaces; import io.kubernetes.client.util.Watch; import io.kubernetes.client.util.Watchable; import io.kubernetes.client.util.generic.GenericKubernetesApi; import io.kubernetes.client.util.generic.options.ListOptions; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import okhttp3.Call; import org.apache.commons.collections4.MapUtils; /** SharedInformerFactory class constructs and caches informers for api types. */ public class SharedInformerFactory { protected Map<Type, SharedIndexInformer> informers; private Map<Type, Future> startedInformers; private ExecutorService informerExecutor; private ApiClient apiClient; /** Constructor w/ default thread pool. */ public SharedInformerFactory() { this(Configuration.getDefaultApiClient().setReadTimeout(0), Executors.newCachedThreadPool()); } /** Constructor w/ api client specified and default thread pool. */ public SharedInformerFactory(ApiClient apiClient) { this(apiClient, Executors.newCachedThreadPool()); } /** * Constructor w/ thread pool specified. * * @param threadPool specified thread pool */ public SharedInformerFactory(ExecutorService threadPool) { this(Configuration.getDefaultApiClient().setReadTimeout(0), threadPool); } /** * Constructor w/ api client and thread pool specified. * * @param client specific api client * @param threadPool specified thread pool */ public SharedInformerFactory(ApiClient client, ExecutorService threadPool) { if (client.getReadTimeout() != 0) { throw new IllegalArgumentException("read timeout of ApiClient must be zero"); } apiClient = client; informerExecutor = threadPool; informers = new HashMap<>(); startedInformers = new HashMap<>(); } /** * Shared index informer for shared index informer. * * @param <ApiType> the type parameter * @param <ApiListType> the type parameter * @param callGenerator the call generator * @param apiTypeClass the api type class * @param apiListTypeClass the api list type class * @return the shared index informer */ public synchronized <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> SharedIndexInformer<ApiType> sharedIndexInformerFor( CallGenerator callGenerator, Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass) { return sharedIndexInformerFor(callGenerator, apiTypeClass, apiListTypeClass, 0); } /** * Constructs and returns a shared index informer w/ resync period specified. But the informer * cache will not be overwritten i.e. only the first registered informer will be kept. * * @param <ApiType> the type parameter * @param <ApiListType> the type parameter * @param callGenerator the call generator * @param apiTypeClass the api type class * @param apiListTypeClass the api list type class * @param resyncPeriodInMillis the resync period in millis * @return the shared index informer */ public synchronized <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> SharedIndexInformer<ApiType> sharedIndexInformerFor( CallGenerator callGenerator, Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass, long resyncPeriodInMillis) { ListerWatcher<ApiType, ApiListType> listerWatcher = listerWatcherFor(callGenerator, apiTypeClass, apiListTypeClass); return sharedIndexInformerFor(listerWatcher, apiTypeClass, resyncPeriodInMillis); } /** * Constructs and returns a shared index informer by specifying lister-watcher. But the informer * cache will not be overwritten on multiple call w/ the the same apiTypeClass i.e. only the first * registered informer will be kept. * * @param <ApiType> the type parameter * @param <ApiListType> the type parameter * @param listerWatcher the lister watcher * @param apiTypeClass the api type class * @param resyncPeriodInMillis the resync period in millis * @return the shared index informer */ public synchronized <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> SharedIndexInformer<ApiType> sharedIndexInformerFor( ListerWatcher<ApiType, ApiListType> listerWatcher, Class<ApiType> apiTypeClass, long resyncPeriodInMillis) { SharedIndexInformer<ApiType> informer = new DefaultSharedIndexInformer<>(apiTypeClass, listerWatcher, resyncPeriodInMillis); this.informers.putIfAbsent(TypeToken.get(apiTypeClass).getType(), informer); return informer; } /** * Constructs and returns a shared index informer by specifying a generic api instance. But the * informer cache will not be overwritten on multiple call w/ the the same apiTypeClass i.e. only * the first registered informer will be kept. * * @param <ApiType> the type parameter * @param <ApiListType> the type parameter * @param genericKubernetesApi the generic kubernetes api * @param apiTypeClass the api type class * @param resyncPeriodInMillis the resync period in millis * @return the shared index informer */ public synchronized <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> SharedIndexInformer<ApiType> sharedIndexInformerFor( GenericKubernetesApi<ApiType, ApiListType> genericKubernetesApi, Class<ApiType> apiTypeClass, long resyncPeriodInMillis) { return sharedIndexInformerFor( genericKubernetesApi, apiTypeClass, resyncPeriodInMillis, Namespaces.NAMESPACE_ALL); } /** * Working the same as {@link SharedInformerFactory#sharedIndexInformerFor} above. * * <p>Constructs and returns a shared index informer for a specific namespace. * * @param <ApiType> the type parameter * @param <ApiListType> the type parameter * @param genericKubernetesApi the generic kubernetes api * @param apiTypeClass the api type class * @param resyncPeriodInMillis the resync period in millis * @param namespace the target namespace * @return the shared index informer */ public synchronized <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> SharedIndexInformer<ApiType> sharedIndexInformerFor( GenericKubernetesApi<ApiType, ApiListType> genericKubernetesApi, Class<ApiType> apiTypeClass, long resyncPeriodInMillis, String namespace) { ListerWatcher<ApiType, ApiListType> listerWatcher = listerWatcherFor(genericKubernetesApi, namespace); return sharedIndexInformerFor(listerWatcher, apiTypeClass, resyncPeriodInMillis); } private <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> ListerWatcher<ApiType, ApiListType> listerWatcherFor( CallGenerator callGenerator, Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass) { if (apiClient.getReadTimeout() > 0) { // set read timeout zero to ensure client doesn't time out apiClient.setReadTimeout(0); } return new ListerWatcher<ApiType, ApiListType>() { @Override public ApiListType list(CallGeneratorParams params) throws ApiException { Call call = callGenerator.generate(params); return (ApiListType) apiClient.execute(call, apiListTypeClass).getData(); } @Override public Watch<ApiType> watch(CallGeneratorParams params) throws ApiException { Call call = callGenerator.generate(params); // bind call with private http client to make sure read timeout is zero. call = apiClient.getHttpClient().newCall(call.request()); return Watch.createWatch( apiClient, call, TypeToken.getParameterized(Watch.Response.class, apiTypeClass).getType()); } }; } private <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> ListerWatcher<ApiType, ApiListType> listerWatcherFor( GenericKubernetesApi<ApiType, ApiListType> genericKubernetesApi, String namespace) { if (apiClient.getReadTimeout() > 0) { // set read timeout zero to ensure client doesn't time out apiClient.setReadTimeout(0); } // TODO: it seems read timeout is determined by genericKubernetesApi instead of above apiClient. return new ListerWatcher<ApiType, ApiListType>() { public ApiListType list(CallGeneratorParams params) throws ApiException { if (Namespaces.NAMESPACE_ALL.equals(namespace)) { return genericKubernetesApi .list( new ListOptions() { { setResourceVersion(params.resourceVersion); setTimeoutSeconds(params.timeoutSeconds); } }) .throwsApiException() .getObject(); } else { return genericKubernetesApi .list( namespace, new ListOptions() { { setResourceVersion(params.resourceVersion); setTimeoutSeconds(params.timeoutSeconds); } }) .throwsApiException() .getObject(); } } public Watchable<ApiType> watch(CallGeneratorParams params) throws ApiException { if (Namespaces.NAMESPACE_ALL.equals(namespace)) { return genericKubernetesApi.watch(); } else { return genericKubernetesApi.watch(namespace); } } }; } /** * Gets existing shared index informer, return null if the requesting informer is never * constructed. * * @param <ApiType> the type parameter * @param apiTypeClass the api type class * @return the existing shared index informer */ public synchronized <ApiType extends KubernetesObject> SharedIndexInformer<ApiType> getExistingSharedIndexInformer(Class<ApiType> apiTypeClass) { return this.informers.get(TypeToken.get(apiTypeClass).getType()); } /** Start all registered informers. */ public synchronized void startAllRegisteredInformers() { if (MapUtils.isEmpty(informers)) { return; } informers.forEach( (informerType, informer) -> startedInformers.computeIfAbsent( informerType, key -> informerExecutor.submit(informer::run))); } /** Stop all registered informers and shut down the thread pool. */ public synchronized void stopAllRegisteredInformers() { stopAllRegisteredInformers(true); } /** * Stop all registered informers. * * @param shutdownThreadPool whether or not to shut down the thread pool. */ public synchronized void stopAllRegisteredInformers(boolean shutdownThreadPool) { if (MapUtils.isEmpty(informers)) { return; } informers.forEach( (informerType, informer) -> { if (startedInformers.remove(informerType) != null) { informer.stop(); } }); if (shutdownThreadPool) { informerExecutor.shutdown(); } } }
Cast to Runnable to avoid compiler error Signed-off-by: Dave Syer <d2258e2d7175ae3e52c06a1018e843daf5809146@vmware.com>
util/src/main/java/io/kubernetes/client/informer/SharedInformerFactory.java
Cast to Runnable to avoid compiler error
Java
apache-2.0
0b6e267611070968d1cff89876de734864aecfc4
0
ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp
package com.ilscipio.scipio.ce.webapp.ftl.template; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.cache.UtilCache; import org.ofbiz.base.util.collections.MapStack; import org.ofbiz.base.util.template.FreeMarkerWorker; import com.ilscipio.scipio.ce.webapp.ftl.context.ContextFtlUtil; import com.ilscipio.scipio.ce.webapp.ftl.template.TemplateInvoker.InvokeOptions.InvokeMode; import freemarker.core.Environment; import freemarker.ext.util.WrapperTemplateModel; import freemarker.template.Configuration; import freemarker.template.ObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import freemarker.template.TemplateScalarModel; /** * Template invoker base class. * Invokes Freemarker template render in a separate render from * any current renderer, using options carried in the instance itself, * using methods such as Ofbiz's FreeMarkerWorker does, and contrary * to the Freemarker <code>?interpret</code> call which inlines * in the current renderer (and therefore poses restrictions). * <p> * This is needed to: * 1) carry the compilation and invocation options around * 2) allow nested Freemarker template renders that behave like separate renders * (and not like inlined interprets like <code>?interpret</code> does) * 3) enable evaluating templates using <code>?string</code> operator from freemarker templates * 4) allow lazy compilation but that still gets cached * <p> * For invoking other templates from within an FTL template, * StringTemplateInvoker can be used which causes the * invocation through the toString() method when this * is wrapped in a StringModel by the ObjectWrapper. * <p> * NOTE: 2017-02: Currently, by default, this relies on BeansWrapper StringModel to call * the StringTemplateInvoker.toString() method to do the invocation from templates; * this is imperfect but allows consistent unwrapping/rewrapping without needing * to modify the ObjectWrapper. HOWEVER this means we only support the "scalar" model for now. * <p> * FIXME?: the reliance on BeansWrapper StringModel means that the bean does not support * the <code>?has_content</code> built-in. This is a limitation caused by the <code>?has_content</code> * built-in that is hardcoded and delegates to BeanModel.empty method (not overridden by StringModel), * which does not invoke the toString method for our invoker object. * This is works out, because <code>?has_content</code> usage on the direct variable would * cause double-rendering and performance problems. * Instead, templates should use <code>??</code> operator or force cast to string * using <code>?string</code> so it is unambiguous at which point the rendering will occur and * will only happen once. * <p> * TODO: in future should have a dedicated TemplateDirectiveModel + TemplateScalarModel hybrid + individuals * in order to be consistent with the <code>?interpret</code> directive behavior (but needs * special code for rewrapping in context, ideally ObjectWrapper.wrap override). * <p> * TODO?: this currently does not support lazy template compilation... don't see much need. */ public class TemplateInvoker { public static final String module = TemplateInvoker.class.getName(); protected final TemplateSource templateSource; protected final InvokeOptions invokeOptions; /** * Carries around the preferred FTL model to use when * this is wrapped by an ObjectWrapper. * CURRENTLY (2017-02), this is always SCALAR. * TODO: more usage * <p> * This is needed here because the FTL unwrapping across macro invocations * will cause information loss about the model or more generally form of the wrapper. * NOTE: ideally this should be honored by the ObjectWrapper implementation, * so for now we are relying on SCALAR and if DIRECTIVE is needed then a * manual wrapping call has to be done. */ protected final WrapperModel preferredModel; public static class InvokeOptions { public enum InvokeMode { /** * Standard, standalone Ofbiz-like invocation, as if using FreeMarkerWorker. */ OFBIZ_STD("ofbiz-std"); /* * Inline, simulation of <code>?interpret</code> directive behavior. * TODO: not sure this will even possible. the point would be * to get ?string support. */ //FTL_INLINE; // TODO private static final Map<String, InvokeMode> nameMap; static { Map<String, InvokeMode> map = new HashMap<>(); for(InvokeMode mode : InvokeMode.values()) { map.put(mode.getName(), mode); } nameMap = map; } private final String name; private InvokeMode(String name) { this.name = name; } public String getName() { return name; } public static InvokeMode fromName(String str) { return nameMap.get(str); } public static InvokeMode fromNameAlways(String str) { InvokeMode mode = fromName(str); if(mode == null) { throw new IllegalArgumentException("Unrecognized template invoke mode: " + str); } return mode; } } protected final InvokeMode invokeMode; protected final Map<String, Object> context; /** * If true, pushes the Ofbiz MapStack context before invoke and pops after. */ protected final Boolean shareScope; protected final Map<String, Object> ctxVars; protected final boolean envOut; public InvokeOptions(InvokeMode invokeMode, Map<String, Object> context, Boolean shareScope, Map<String, Object> ctxVars, boolean envOut) { this.invokeMode = invokeMode; this.context = context; this.shareScope = shareScope; this.ctxVars = ctxVars; this.envOut = envOut; } public InvokeOptions(InvokeMode invokeMode, Boolean shareScope, Map<String, Object> ctxVars) { this(invokeMode, null, shareScope, ctxVars, false); } public InvokeMode getInvokeMode() { return invokeMode; } /** * The context object to use. By default the well-known MapStack is used. */ public Map<String, Object> getContext() { return context; } public Boolean getShareScope() { return shareScope; } public Boolean getShareScope(Boolean defaultVal) { return shareScope != null ? shareScope : defaultVal; } /** * NOTE: these may already be TemplateModels, or not. */ public Map<String, Object> getCtxVars() { return ctxVars; } public boolean isEnvOut() { return envOut; } } /** * FTL TemplateModel type to wrap this TemplateInvoker in. * <p> * NOTE: <code>SCALAR</code> is unspecific between StringModel-wrapped StringTemplateInvoker * and dedicated TemplateScalarModel implementation. * <p> * Currently (2017-02) for SCALAR our code will be using StringModel-wrapped StringTemplateInvoker. */ public enum WrapperModel { SCALAR("scalar"), DIRECTIVE("directive"), HYBRID("hybrid"); private static final Map<String, WrapperModel> nameMap; static { Map<String, WrapperModel> map = new HashMap<>(); for(WrapperModel mode : WrapperModel.values()) { map.put(mode.getName(), mode); } nameMap = map; } private final String name; private WrapperModel(String name) { this.name = name; } public String getName() { return name; } public static WrapperModel fromName(String str) { return nameMap.get(str); } public static WrapperModel fromNameAlways(String str) { WrapperModel mode = fromName(str); if(mode == null) { throw new IllegalArgumentException("Unrecognized template invoke wrapper model: " + str); } return mode; } } protected TemplateInvoker(TemplateSource templateSource, InvokeOptions invokeOptions, WrapperModel preferredModel) { this.templateSource = templateSource; this.invokeOptions = invokeOptions; this.preferredModel = preferredModel; } /* ***************************************************** */ /* Factory Methods */ /* ***************************************************** */ /** * Gets a standard template invoker. */ public static TemplateInvoker getInvoker(TemplateSource templateSource, InvokeOptions invokeOptions, WrapperModel preferredModel) throws TemplateException, IOException { return new TemplateInvoker(templateSource, invokeOptions, preferredModel); } /** * Gets a template invoker same as standard except its toString() method invokes rendering. */ public static TemplateInvoker getStringInvoker(TemplateSource templateSource, InvokeOptions invokeOptions, WrapperModel preferredModel) throws TemplateException, IOException { return new StringTemplateInvoker(templateSource, invokeOptions, preferredModel); } /* ***************************************************** */ /* Main Invocation Calls */ /* ***************************************************** */ /** * Invokes rendering and outputs to Writer. */ public void invoke(Writer out) throws TemplateException, IOException { Template template = getTemplate(); Map<String, Object> context = getContext(); if (invokeOptions.getInvokeMode() == null || invokeOptions.getInvokeMode() == InvokeMode.OFBIZ_STD) { Boolean protectScope = !invokeOptions.getShareScope(false); if (!(context instanceof MapStack)) protectScope = false; if (protectScope) { ((MapStack<String>) context).push(); } try { if (invokeOptions.getCtxVars() != null) { context.putAll(invokeOptions.getCtxVars()); } FreeMarkerWorker.renderTemplate(template, context, out); } finally { if (protectScope) { ((MapStack<String>) context).pop(); } } } else { throw new UnsupportedOperationException("Unsupported template invoke mode: " + invokeOptions.invokeMode); } } /** * Invokes rendering and returns as a String. */ public String invoke() throws TemplateException, IOException { StringWriter sw = new StringWriter(); invoke(sw); return sw.toString(); } /* ***************************************************** */ /* Getters and Helpers */ /* ***************************************************** */ public Template getTemplate() throws TemplateException, IOException { return templateSource.getTemplate(); } protected TemplateSource getTemplateSource() throws TemplateException, IOException { return templateSource; } public InvokeOptions getInvokeOptions() { return invokeOptions; } public WrapperModel getPreferredModel() { return preferredModel; } protected Map<String, Object> getContext() { Map<String, Object> context = invokeOptions.getContext(); if (context == null) { try { context = ContextFtlUtil.getContext(FreeMarkerWorker.getCurrentEnvironment()); } catch (Exception e) { Debug.logError(e, module); } } if (context == null) { context = MapStack.create(); } return context; } /* ***************************************************** */ /* Specific Invoker Implementations */ /* ***************************************************** */ /** * Variant of TemplateInvoker that invokes rendering when toString() is called. */ public static class StringTemplateInvoker extends TemplateInvoker { protected StringTemplateInvoker(TemplateSource templateSource, InvokeOptions invokeOptions, WrapperModel preferredModel) { super(templateSource, invokeOptions, preferredModel); } @Override public String toString() { try { // NOTE: this env check really belongs in the TemplateModels below, but because of the bean wrapper // mode, it has to be here. if (this.getInvokeOptions().isEnvOut()) { Environment env = FreeMarkerWorker.getCurrentEnvironment(); if (env != null) { Writer out = env.getOut(); if (out != null) { this.invoke(out); return ""; } } } return this.invoke(); } catch (TemplateException e) { Debug.logError(e, module); return ""; } catch (IOException e) { Debug.logError(e, module); return ""; } } } /* ***************************************************** */ /* Invoker Freemarker Wrappers */ /* ***************************************************** */ /** * Wraps the TemplateInvoker in an appropriate TemplateModel, using invoker's preferred model. * Can be called manually as this logic may not be present in <code>ObjectWrapper.wrap</code>. * <p> * TODO: currently (2017-02) this always wraps using StringModel, done by most of the * default object wrapper impls. */ @SuppressWarnings("unchecked") public static <T extends TemplateModel> T wrap(TemplateInvoker invoker, ObjectWrapper objectWrapper) throws TemplateModelException { return wrap(invoker, objectWrapper, invoker.getPreferredModel()); } /** * Wraps the TemplateInvoker in an appropriate TemplateModel, using explicit model type. * Can be called manually as this logic may not be present in <code>ObjectWrapper.wrap</code>. */ @SuppressWarnings("unchecked") public static <T extends TemplateModel> T wrap(TemplateInvoker invoker, ObjectWrapper objectWrapper, WrapperModel targetModel) throws TemplateModelException { if (targetModel == null || targetModel == WrapperModel.SCALAR) { if (invoker instanceof StringTemplateInvoker) { // TODO: REVISIT: in this case, currently relying on StringModel and ignoring ScalarInvokerWrapper. // This case currently covers all the practical usage in templates and CMS... // NOTE: if this method were called from ObjectWrapper.wrap, would cause endless loop... return (T) objectWrapper.wrap(invoker); } else { return (T) new ScalarInvokerWrapper(invoker); } } else if (targetModel == WrapperModel.DIRECTIVE) { return (T) new DirectiveInvokerWrapper(invoker); } else if (targetModel == WrapperModel.HYBRID) { return (T) new HybridInvokerWrapper(invoker); } throw new UnsupportedOperationException("Unsupported template invoker FTL wrapper model: " + targetModel); } /** * Custom Freemarker wrapper TemplateModel around the TemplateInvoker. * <p> * TODO: currently this is mainly for testing; will be using StringModel-wrapped * StringInvokerWrapper in the interim. */ public static abstract class InvokerWrapper implements TemplateModel, WrapperTemplateModel { protected final TemplateInvoker invoker; protected InvokerWrapper(TemplateInvoker invoker) { this.invoker = invoker; } @Override public Object getWrappedObject() { return invoker; } protected String invokeAsString() throws TemplateModelException { try { return invoker.invoke(); } catch (TemplateException e) { throw new TemplateModelException(e); } catch (IOException e) { throw new TemplateModelException(e); } } } public static class DirectiveInvokerWrapper extends InvokerWrapper implements TemplateDirectiveModel { protected DirectiveInvokerWrapper(TemplateInvoker invoker) { super(invoker); } @Override public void execute(Environment env, Map args, TemplateModel[] modelArgs, TemplateDirectiveBody body) throws TemplateException, IOException { invoker.invoke(env.getOut()); } } public static class ScalarInvokerWrapper extends InvokerWrapper implements TemplateScalarModel { protected ScalarInvokerWrapper(TemplateInvoker invoker) { super(invoker); } @Override public String getAsString() throws TemplateModelException { return invokeAsString(); } } public static class HybridInvokerWrapper extends InvokerWrapper implements TemplateDirectiveModel, TemplateScalarModel { protected HybridInvokerWrapper(TemplateInvoker invoker) { super(invoker); } @Override public void execute(Environment env, Map args, TemplateModel[] modelArgs, TemplateDirectiveBody body) throws TemplateException, IOException { invoker.invoke(env.getOut()); } @Override public String getAsString() throws TemplateModelException { return invokeAsString(); } } }
framework/webapp/src/com/ilscipio/scipio/ce/webapp/ftl/template/TemplateInvoker.java
package com.ilscipio.scipio.ce.webapp.ftl.template; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.cache.UtilCache; import org.ofbiz.base.util.collections.MapStack; import org.ofbiz.base.util.template.FreeMarkerWorker; import com.ilscipio.scipio.ce.webapp.ftl.context.ContextFtlUtil; import com.ilscipio.scipio.ce.webapp.ftl.template.TemplateInvoker.InvokeOptions.InvokeMode; import freemarker.core.Environment; import freemarker.ext.util.WrapperTemplateModel; import freemarker.template.Configuration; import freemarker.template.ObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import freemarker.template.TemplateScalarModel; /** * Template invoker base class. * Invokes Freemarker template render in a separate render from * any current renderer, using options carried in the instance itself, * using methods such as Ofbiz's FreeMarkerWorker does, and contrary * to the Freemarker <code>?interpret</code> call which inlines * in the current renderer (and therefore poses restrictions). * <p> * This is needed to: * 1) carry the compilation and invocation options around * 2) allow nested Freemarker template renders that behave like separate renders * (and not like inlined interprets like <code>?interpret</code> does) * 3) enable evaluating templates using <code>?string</code> operator from freemarker templates * 4) allow lazy compilation but that still gets cached * <p> * For invoking other templates from within an FTL template, * StringTemplateInvoker can be used which causes the * invocation through the toString() method when this * is wrapped in a StringModel by the ObjectWrapper. * <p> * NOTE: 2017-02: Currently, by default, this relies on BeansWrapper StringModel to call * the StringTemplateInvoker.toString() method to do the invocation from templates; * this is imperfect but allows consistent unwrapping/rewrapping without needing * to modify the ObjectWrapper. HOWEVER this means we only support the "scalar" model for now. * <p> * FIXME: the reliance on BeansWrapper StringModel means that the bean does not support * the <code>?has_content</code> built-in. This is a limitation caused by the <code>?has_content</code> * built-in that is hardcoded and delegates to BeanModel.empty method (not overridden by StringModel), * which does not invoke the toString method for our invoker object. * This is works out, because <code>?has_content</code> usage on the direct variable would * cause double-rendering and performance problems. * Instead, templates should use <code>??</code> operator or force cast to string * using <code>?string</code> so it is unambiguous at which point the rendering will occur and * will only happen once. * <p> * TODO: in future should have a dedicated TemplateDirectiveModel + TemplateScalarModel hybrid + individuals * in order to be consistent with the <code>?interpret</code> directive behavior (but needs * special code for rewrapping in context, ideally ObjectWrapper.wrap override). * <p> * TODO?: this currently does not support lazy template compilation... don't see much need. */ public class TemplateInvoker { public static final String module = TemplateInvoker.class.getName(); protected final TemplateSource templateSource; protected final InvokeOptions invokeOptions; /** * Carries around the preferred FTL model to use when * this is wrapped by an ObjectWrapper. * CURRENTLY (2017-02), this is always SCALAR. * TODO: more usage * <p> * This is needed here because the FTL unwrapping across macro invocations * will cause information loss about the model or more generally form of the wrapper. * NOTE: ideally this should be honored by the ObjectWrapper implementation, * so for now we are relying on SCALAR and if DIRECTIVE is needed then a * manual wrapping call has to be done. */ protected final WrapperModel preferredModel; public static class InvokeOptions { public enum InvokeMode { /** * Standard, standalone Ofbiz-like invocation, as if using FreeMarkerWorker. */ OFBIZ_STD("ofbiz-std"); /* * Inline, simulation of <code>?interpret</code> directive behavior. * TODO: not sure this will even possible. the point would be * to get ?string support. */ //FTL_INLINE; // TODO private static final Map<String, InvokeMode> nameMap; static { Map<String, InvokeMode> map = new HashMap<>(); for(InvokeMode mode : InvokeMode.values()) { map.put(mode.getName(), mode); } nameMap = map; } private final String name; private InvokeMode(String name) { this.name = name; } public String getName() { return name; } public static InvokeMode fromName(String str) { return nameMap.get(str); } public static InvokeMode fromNameAlways(String str) { InvokeMode mode = fromName(str); if(mode == null) { throw new IllegalArgumentException("Unrecognized template invoke mode: " + str); } return mode; } } protected final InvokeMode invokeMode; protected final Map<String, Object> context; /** * If true, pushes the Ofbiz MapStack context before invoke and pops after. */ protected final Boolean shareScope; protected final Map<String, Object> ctxVars; protected final boolean envOut; public InvokeOptions(InvokeMode invokeMode, Map<String, Object> context, Boolean shareScope, Map<String, Object> ctxVars, boolean envOut) { this.invokeMode = invokeMode; this.context = context; this.shareScope = shareScope; this.ctxVars = ctxVars; this.envOut = envOut; } public InvokeOptions(InvokeMode invokeMode, Boolean shareScope, Map<String, Object> ctxVars) { this(invokeMode, null, shareScope, ctxVars, false); } public InvokeMode getInvokeMode() { return invokeMode; } /** * The context object to use. By default the well-known MapStack is used. */ public Map<String, Object> getContext() { return context; } public Boolean getShareScope() { return shareScope; } public Boolean getShareScope(Boolean defaultVal) { return shareScope != null ? shareScope : defaultVal; } /** * NOTE: these may already be TemplateModels, or not. */ public Map<String, Object> getCtxVars() { return ctxVars; } public boolean isEnvOut() { return envOut; } } /** * FTL TemplateModel type to wrap this TemplateInvoker in. * <p> * NOTE: <code>SCALAR</code> is unspecific between StringModel-wrapped StringTemplateInvoker * and dedicated TemplateScalarModel implementation. * <p> * Currently (2017-02) for SCALAR our code will be using StringModel-wrapped StringTemplateInvoker. */ public enum WrapperModel { SCALAR("scalar"), DIRECTIVE("directive"), HYBRID("hybrid"); private static final Map<String, WrapperModel> nameMap; static { Map<String, WrapperModel> map = new HashMap<>(); for(WrapperModel mode : WrapperModel.values()) { map.put(mode.getName(), mode); } nameMap = map; } private final String name; private WrapperModel(String name) { this.name = name; } public String getName() { return name; } public static WrapperModel fromName(String str) { return nameMap.get(str); } public static WrapperModel fromNameAlways(String str) { WrapperModel mode = fromName(str); if(mode == null) { throw new IllegalArgumentException("Unrecognized template invoke wrapper model: " + str); } return mode; } } protected TemplateInvoker(TemplateSource templateSource, InvokeOptions invokeOptions, WrapperModel preferredModel) { this.templateSource = templateSource; this.invokeOptions = invokeOptions; this.preferredModel = preferredModel; } /* ***************************************************** */ /* Factory Methods */ /* ***************************************************** */ /** * Gets a standard template invoker. */ public static TemplateInvoker getInvoker(TemplateSource templateSource, InvokeOptions invokeOptions, WrapperModel preferredModel) throws TemplateException, IOException { return new TemplateInvoker(templateSource, invokeOptions, preferredModel); } /** * Gets a template invoker same as standard except its toString() method invokes rendering. */ public static TemplateInvoker getStringInvoker(TemplateSource templateSource, InvokeOptions invokeOptions, WrapperModel preferredModel) throws TemplateException, IOException { return new StringTemplateInvoker(templateSource, invokeOptions, preferredModel); } /* ***************************************************** */ /* Main Invocation Calls */ /* ***************************************************** */ /** * Invokes rendering and outputs to Writer. */ public void invoke(Writer out) throws TemplateException, IOException { Template template = getTemplate(); Map<String, Object> context = getContext(); if (invokeOptions.getInvokeMode() == null || invokeOptions.getInvokeMode() == InvokeMode.OFBIZ_STD) { Boolean protectScope = !invokeOptions.getShareScope(false); if (!(context instanceof MapStack)) protectScope = false; if (protectScope) { ((MapStack<String>) context).push(); } try { if (invokeOptions.getCtxVars() != null) { context.putAll(invokeOptions.getCtxVars()); } FreeMarkerWorker.renderTemplate(template, context, out); } finally { if (protectScope) { ((MapStack<String>) context).pop(); } } } else { throw new UnsupportedOperationException("Unsupported template invoke mode: " + invokeOptions.invokeMode); } } /** * Invokes rendering and returns as a String. */ public String invoke() throws TemplateException, IOException { StringWriter sw = new StringWriter(); invoke(sw); return sw.toString(); } /* ***************************************************** */ /* Getters and Helpers */ /* ***************************************************** */ public Template getTemplate() throws TemplateException, IOException { return templateSource.getTemplate(); } protected TemplateSource getTemplateSource() throws TemplateException, IOException { return templateSource; } public InvokeOptions getInvokeOptions() { return invokeOptions; } public WrapperModel getPreferredModel() { return preferredModel; } protected Map<String, Object> getContext() { Map<String, Object> context = invokeOptions.getContext(); if (context == null) { try { context = ContextFtlUtil.getContext(FreeMarkerWorker.getCurrentEnvironment()); } catch (Exception e) { Debug.logError(e, module); } } if (context == null) { context = MapStack.create(); } return context; } /* ***************************************************** */ /* Specific Invoker Implementations */ /* ***************************************************** */ /** * Variant of TemplateInvoker that invokes rendering when toString() is called. */ public static class StringTemplateInvoker extends TemplateInvoker { protected StringTemplateInvoker(TemplateSource templateSource, InvokeOptions invokeOptions, WrapperModel preferredModel) { super(templateSource, invokeOptions, preferredModel); } @Override public String toString() { try { // NOTE: this env check really belongs in the TemplateModels below, but because of the bean wrapper // mode, it has to be here. if (this.getInvokeOptions().isEnvOut()) { Environment env = FreeMarkerWorker.getCurrentEnvironment(); if (env != null) { Writer out = env.getOut(); if (out != null) { this.invoke(out); return ""; } } } return this.invoke(); } catch (TemplateException e) { Debug.logError(e, module); return ""; } catch (IOException e) { Debug.logError(e, module); return ""; } } } /* ***************************************************** */ /* Invoker Freemarker Wrappers */ /* ***************************************************** */ /** * Wraps the TemplateInvoker in an appropriate TemplateModel, using invoker's preferred model. * Can be called manually as this logic may not be present in <code>ObjectWrapper.wrap</code>. * <p> * TODO: currently (2017-02) this always wraps using StringModel, done by most of the * default object wrapper impls. */ @SuppressWarnings("unchecked") public static <T extends TemplateModel> T wrap(TemplateInvoker invoker, ObjectWrapper objectWrapper) throws TemplateModelException { return wrap(invoker, objectWrapper, invoker.getPreferredModel()); } /** * Wraps the TemplateInvoker in an appropriate TemplateModel, using explicit model type. * Can be called manually as this logic may not be present in <code>ObjectWrapper.wrap</code>. */ @SuppressWarnings("unchecked") public static <T extends TemplateModel> T wrap(TemplateInvoker invoker, ObjectWrapper objectWrapper, WrapperModel targetModel) throws TemplateModelException { if (targetModel == null || targetModel == WrapperModel.SCALAR) { if (invoker instanceof StringTemplateInvoker) { // TODO: REVISIT: in this case, currently relying on StringModel and ignoring ScalarInvokerWrapper. // This case currently covers all the practical usage in templates and CMS... // NOTE: if this method were called from ObjectWrapper.wrap, would cause endless loop... return (T) objectWrapper.wrap(invoker); } else { return (T) new ScalarInvokerWrapper(invoker); } } else if (targetModel == WrapperModel.DIRECTIVE) { return (T) new DirectiveInvokerWrapper(invoker); } else if (targetModel == WrapperModel.HYBRID) { return (T) new HybridInvokerWrapper(invoker); } throw new UnsupportedOperationException("Unsupported template invoker FTL wrapper model: " + targetModel); } /** * Custom Freemarker wrapper TemplateModel around the TemplateInvoker. * <p> * TODO: currently this is mainly for testing; will be using StringModel-wrapped * StringInvokerWrapper in the interim. */ public static abstract class InvokerWrapper implements TemplateModel, WrapperTemplateModel { protected final TemplateInvoker invoker; protected InvokerWrapper(TemplateInvoker invoker) { this.invoker = invoker; } @Override public Object getWrappedObject() { return invoker; } protected String invokeAsString() throws TemplateModelException { try { return invoker.invoke(); } catch (TemplateException e) { throw new TemplateModelException(e); } catch (IOException e) { throw new TemplateModelException(e); } } } public static class DirectiveInvokerWrapper extends InvokerWrapper implements TemplateDirectiveModel { protected DirectiveInvokerWrapper(TemplateInvoker invoker) { super(invoker); } @Override public void execute(Environment env, Map args, TemplateModel[] modelArgs, TemplateDirectiveBody body) throws TemplateException, IOException { invoker.invoke(env.getOut()); } } public static class ScalarInvokerWrapper extends InvokerWrapper implements TemplateScalarModel { protected ScalarInvokerWrapper(TemplateInvoker invoker) { super(invoker); } @Override public String getAsString() throws TemplateModelException { return invokeAsString(); } } public static class HybridInvokerWrapper extends InvokerWrapper implements TemplateDirectiveModel, TemplateScalarModel { protected HybridInvokerWrapper(TemplateInvoker invoker) { super(invoker); } @Override public void execute(Environment env, Map args, TemplateModel[] modelArgs, TemplateDirectiveBody body) throws TemplateException, IOException { invoker.invoke(env.getOut()); } @Override public String getAsString() throws TemplateModelException { return invokeAsString(); } } }
Refs #1153 cms: TemplateInvoker: added FIXME explanation as to why ?has_content will not work on these variables... for time being, this works out because it was going to cause other problems anyway git-svn-id: 6c0edb9fdd085beb7f3b78cf385b6ddede550bd9@15194 55bbc10b-e964-4c8f-a844-a62c6f7d3c80
framework/webapp/src/com/ilscipio/scipio/ce/webapp/ftl/template/TemplateInvoker.java
Refs #1153 cms: TemplateInvoker: added FIXME explanation as to why ?has_content will not work on these variables... for time being, this works out because it was going to cause other problems anyway
Java
apache-2.0
4ec294ceb1052a5c2afa3cd9172731f2ff1d1bb1
0
brain-bugs/Klendathu
package de.hbt.hackathon.rtb.base.message.input; import de.hbt.hackathon.rtb.base.type.ObjectType; public class RadarMessage extends InputMessage { private final double radarDistance; private final double radarAngle; // in radians private final ObjectType objectType; private RadarMessage(double radarDistance, double radarAngle, ObjectType objectType) { this.radarDistance = radarDistance; this.radarAngle = radarAngle; this.objectType = objectType; } public double getRadarDistance() { return radarDistance; } public double getRadarAngle() { return radarAngle; } public ObjectType getObjectType() { return objectType; } public static RadarMessage valueOf(String[] args) { double radarDistance = Double.valueOf(args[1]); ObjectType objectType = ObjectType.fromCode(Integer.valueOf(args[2])); double radarAngle = Double.valueOf(args[3]); return new RadarMessage(radarDistance, radarAngle, objectType); } }
base/src/main/java/de/hbt/hackathon/rtb/base/message/input/RadarMessage.java
package de.hbt.hackathon.rtb.base.message.input; import de.hbt.hackathon.rtb.base.type.ObjectType; public class RadarMessage extends InputMessage { private final double radarDistance; private final double radarAngle; // in radians private final ObjectType objectType; private RadarMessage(double radarDistance, double radarAngle, ObjectType objectType) { this.radarDistance = radarDistance; this.radarAngle = radarAngle; this.objectType = objectType; } public double getRadarDistance() { return radarDistance; } public double getRadarAngle() { return radarAngle; } public ObjectType getObjectType() { return objectType; } public static RadarMessage valueOf(String[] args) { double radarDistance = Double.valueOf(args[1]); double radarAngle = Double.valueOf(args[2]); ObjectType objectType = ObjectType.fromCode(Integer.valueOf(args[3])); return new RadarMessage(radarDistance, radarAngle, objectType); } }
Bugfix for radar message.
base/src/main/java/de/hbt/hackathon/rtb/base/message/input/RadarMessage.java
Bugfix for radar message.
Java
apache-2.0
527f265fba79719f86f6e567cb8ec580bbe9b830
0
binhnv/azkaban,azkaban/azkaban,johnyu0520/azkaban,azkaban/azkaban,erwa/azkaban,binhnv/azkaban,azkaban/azkaban,mariacioffi/azkaban,erwa/azkaban,HappyRay/azkaban,mariacioffi/azkaban,chengren311/azkaban,evlstyle/azkaban,davidzchen/azkaban,poporisil/azkaban3,HappyRay/azkaban,mradamlacey/azkaban,johnyu0520/azkaban,erwa/azkaban,poporisil/azkaban3,mradamlacey/azkaban,researchgate/azkaban,binhnv/azkaban,erwa/azkaban,HappyRay/azkaban,reallocf/azkaban,HappyRay/azkaban,relateiq/azkaban,mariacioffi/azkaban,johnyu0520/azkaban,researchgate/azkaban,evlstyle/azkaban,HappyRay/azkaban,mradamlacey/azkaban,HappyRay/azkaban,relateiq/azkaban,evlstyle/azkaban,jackrjli/azkaban,davidzchen/azkaban,inoviaazkaban/azkaban,chengren311/azkaban,sunghyuk/azkaban,davidzchen/azkaban,inoviaazkaban/azkaban,azkaban/azkaban,logiclord/azkaban,erwa/azkaban,jackrjli/azkaban,sunghyuk/azkaban,reallocf/azkaban,relateiq/azkaban,binhnv/azkaban,researchgate/azkaban,logiclord/azkaban,poporisil/azkaban3,logiclord/azkaban,reallocf/azkaban,evlstyle/azkaban,sunghyuk/azkaban,azkaban/azkaban,azkaban/azkaban,poporisil/azkaban3,jackrjli/azkaban,inoviaazkaban/azkaban,jackrjli/azkaban,chengren311/azkaban,chengren311/azkaban,reallocf/azkaban,poporisil/azkaban3,chengren311/azkaban,binhnv/azkaban,mradamlacey/azkaban,johnyu0520/azkaban,relateiq/azkaban,researchgate/azkaban,mariacioffi/azkaban,reallocf/azkaban,logiclord/azkaban,jackrjli/azkaban,sunghyuk/azkaban,mradamlacey/azkaban,davidzchen/azkaban,mariacioffi/azkaban,sunghyuk/azkaban
/* * Copyright 2015 LinkedIn 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 azkaban.execapp; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import azkaban.executor.ExecutorInfo; import azkaban.utils.JSONUtils; public class ServerStatisticsServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final int cacheTimeInMilliseconds = 1000; private static final Logger logger = Logger.getLogger(ServerStatisticsServlet.class); private static final String noCacheParamName = "nocache"; protected static long lastRefreshedTime = 0; protected static ExecutorInfo cachedstats = null; /** * Handle all get request to Statistics Servlet {@inheritDoc} * * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean noCache = null!= req && Boolean.valueOf(req.getParameter(noCacheParamName)); if (noCache || System.currentTimeMillis() - lastRefreshedTime > cacheTimeInMilliseconds){ this.populateStatistics(noCache); } JSONUtils.toJSON(cachedstats, resp.getOutputStream(), true); } /** * fill the result set with the percent of the remaining system memory on the server. * @param stats reference to the result container which contains all the results, this specific method * will only work work on the property "remainingMemory" and "remainingMemoryPercent". * * NOTE: * a double value will be used to present the remaining memory, * a returning value of '55.6' means 55.6% */ protected void fillRemainingMemoryPercent(ExecutorInfo stats){ if (new File("/bin/bash").exists() && new File("/bin/cat").exists() && new File("/bin/grep").exists() && new File("/proc/meminfo").exists()) { java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder("/bin/bash", "-c", "/bin/cat /proc/meminfo | grep -E \"MemTotal|MemFree|Buffers|Cached|SwapCached\""); try { ArrayList<String> output = new ArrayList<String>(); Process process = processBuilder.start(); process.waitFor(); InputStream inputStream = process.getInputStream(); try { java.io.BufferedReader reader = new java.io.BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = reader.readLine()) != null) { output.add(line); } }finally { inputStream.close(); } long totalMemory = 0; long totalFreeMemory = 0; long parsedResult = 0; // process the output from bash call. // we expect the result from the bash call to be something like following - // MemTotal: 65894264 kB // MemFree: 57753844 kB // Buffers: 305552 kB // Cached: 3802432 kB // SwapCached: 0 kB // Note : total free memory = freeMemory + cached + buffers + swapCached if (output.size() > 0) { for (String result : output){ // find the total memory and value the variable. if (result.contains("MemTotal") && result.split("\\s+").length > 2){ try { totalMemory = Long.parseLong(result.split("\\s+")[1]); logger.debug("Total memory : " + totalMemory); }catch(NumberFormatException e){ logger.error("yielding 0 for total memory as output is invalid -" + result); } } // find the free memory. if (result.contains("MemFree") && result.split("\\s+").length > 2){ try { parsedResult = Long.parseLong(result.split("\\s+")[1]); logger.debug("Free memory : " + parsedResult); totalFreeMemory += parsedResult; }catch(NumberFormatException e){ logger.error("yielding 0 for free memory as output is invalid -" + result); } } // find the Buffers. if (result.contains("Buffers") && result.split("\\s+").length > 2){ try { parsedResult = Long.parseLong(result.split("\\s+")[1]); logger.debug("Buffers : " + parsedResult); totalFreeMemory += parsedResult; }catch(NumberFormatException e){ logger.error("yielding 0 for Buffers as output is invalid -" + result); } } // find the Cached. if (result.contains("Cached") && result.split("\\s+").length > 2){ try { parsedResult = Long.parseLong(result.split("\\s+")[1]); logger.debug("Cached : " + parsedResult); totalFreeMemory += parsedResult; }catch(NumberFormatException e){ logger.error("yielding 0 for Cached as output is invalid -" + result); } } // find the SwapCached. if (result.contains("SwapCached") && result.split("\\s+").length > 2){ try { parsedResult = Long.parseLong(result.split("\\s+")[1]); logger.debug("SwapCached : " + parsedResult); totalFreeMemory += parsedResult; }catch(NumberFormatException e){ logger.error("yielding 0 for SwapCached as output is invalid -" + result); } } } }else { logger.error("failed to get total/free memory info as the bash call returned invalid result."); } // the number got from the proc file is in KBs we want to see the number in MBs so we are dividing it by 1024. stats.setRemainingMemoryInMB(totalFreeMemory/1024); stats.setRemainingMemoryPercent(totalMemory == 0 ? 0 : ((double)totalFreeMemory / (double)totalMemory)*100); } catch (Exception ex){ logger.error("failed fetch system memory info " + "as exception is captured when fetching result from bash call. Ex -" + ex.getMessage()); } } else { logger.error("failed fetch system memory info, one or more files from the following list are missing - " + "'/bin/bash'," + "'/bin/cat'," +"'/proc/loadavg'"); } } /** * call the data providers to fill the returning data container for statistics data. * This function refreshes the static cached copy of data in case if necessary. * */ protected synchronized void populateStatistics(boolean noCache){ //check again before starting the work. if (noCache || System.currentTimeMillis() - lastRefreshedTime > cacheTimeInMilliseconds){ final ExecutorInfo stats = new ExecutorInfo(); fillRemainingMemoryPercent(stats); fillRemainingFlowCapacityAndLastDispatchedTime(stats); fillCpuUsage(stats); cachedstats = stats; lastRefreshedTime = System.currentTimeMillis(); } } /** * fill the result set with the remaining flow capacity . * @param stats reference to the result container which contains all the results, this specific method * will only work on the property "remainingFlowCapacity". */ protected void fillRemainingFlowCapacityAndLastDispatchedTime(ExecutorInfo stats){ AzkabanExecutorServer server = AzkabanExecutorServer.getApp(); if (server != null){ FlowRunnerManager runnerMgr = AzkabanExecutorServer.getApp().getFlowRunnerManager(); int assignedFlows = runnerMgr.getNumRunningFlows() + runnerMgr.getNumQueuedFlows(); stats.setRemainingFlowCapacity(runnerMgr.getMaxNumRunningFlows() - assignedFlows); stats.setNumberOfAssignedFlows(assignedFlows); stats.setLastDispatchedTime(runnerMgr.getLastFlowSubmittedTime()); }else { logger.error("failed to get data for remaining flow capacity or LastDispatchedTime" + " as the AzkabanExecutorServer has yet been initialized."); } } /**<pre> * fill the result set with the CPU usage . * Note : As the 'Top' bash call doesn't yield accurate result for the system load, * the implementation has been changed to load from the "proc/loadavg" which keeps * the moving average of the system load, we are pulling the average for the recent 1 min. *</pre> * @param stats reference to the result container which contains all the results, this specific method * will only work on the property "cpuUsage". */ protected void fillCpuUsage(ExecutorInfo stats){ if (new File("/bin/bash").exists() && new File("/bin/cat").exists() && new File("/proc/loadavg").exists()) { java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder("/bin/bash", "-c", "/bin/cat /proc/loadavg"); try { ArrayList<String> output = new ArrayList<String>(); Process process = processBuilder.start(); process.waitFor(); InputStream inputStream = process.getInputStream(); try { java.io.BufferedReader reader = new java.io.BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = reader.readLine()) != null) { output.add(line); } }finally { inputStream.close(); } // process the output from bash call. if (output.size() > 0) { String[] splitedresult = output.get(0).split("\\s+"); double cpuUsage = 0.0; try { cpuUsage = Double.parseDouble(splitedresult[0]); }catch(NumberFormatException e){ logger.error("yielding 0.0 for CPU usage as output is invalid -" + output.get(0)); } logger.info("System load : " + cpuUsage); stats.setCpuUpsage(cpuUsage); } } catch (Exception ex){ logger.error("failed fetch system load info " + "as exception is captured when fetching result from bash call. Ex -" + ex.getMessage()); } } else { logger.error("failed fetch system load info, one or more files from the following list are missing - " + "'/bin/bash'," + "'/bin/cat'," +"'/proc/loadavg'"); } } }
azkaban-execserver/src/main/java/azkaban/execapp/ServerStatisticsServlet.java
/* * Copyright 2015 LinkedIn 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 azkaban.execapp; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import azkaban.executor.ExecutorInfo; import azkaban.utils.JSONUtils; public class ServerStatisticsServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final int cacheTimeInMilliseconds = 1000; private static final Logger logger = Logger.getLogger(ServerStatisticsServlet.class); private static final String noCacheParamName = "nocache"; protected static long lastRefreshedTime = 0; protected static ExecutorInfo cachedstats = null; /** * Handle all get request to Statistics Servlet {@inheritDoc} * * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean noCache = null!= req && Boolean.valueOf(req.getParameter(noCacheParamName)); if (noCache || System.currentTimeMillis() - lastRefreshedTime > cacheTimeInMilliseconds){ this.populateStatistics(noCache); } JSONUtils.toJSON(cachedstats, resp.getOutputStream(), true); } /** * fill the result set with the percent of the remaining system memory on the server. * @param stats reference to the result container which contains all the results, this specific method * will only work work on the property "remainingMemory" and "remainingMemoryPercent". * * NOTE: * a double value will be used to present the remaining memory, * a returning value of '55.6' means 55.6% */ protected void fillRemainingMemoryPercent(ExecutorInfo stats){ if (new File("/bin/bash").exists() && new File("/bin/cat").exists() && new File("/bin/grep").exists() && new File("/proc/meminfo").exists()) { java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder("/bin/bash", "-c", "/bin/cat /proc/meminfo | grep -E \"MemTotal|MemFree|Buffers|Cached|SwapCached\""); try { ArrayList<String> output = new ArrayList<String>(); Process process = processBuilder.start(); process.waitFor(); InputStream inputStream = process.getInputStream(); try { java.io.BufferedReader reader = new java.io.BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = reader.readLine()) != null) { output.add(line); } }finally { inputStream.close(); } long totalMemory = 0; long totalFreeMemory = 0; long parsedResult = 0; // process the output from bash call. // we expect the result from the bash call to be something like following - // MemTotal: 65894264 kB // MemFree: 57753844 kB // Buffers: 305552 kB // Cached: 3802432 kB // SwapCached: 0 kB // Note : total free memory = freeMemory + cached + buffers + swapCached if (output.size() == 5) { for (String result : output){ // find the total memory and value the variable. if (result.contains("MemTotal") && result.split("\\s+").length > 2){ try { totalMemory = Long.parseLong(result.split("\\s+")[1]); logger.debug("Total memory : " + totalMemory); }catch(NumberFormatException e){ logger.error("yielding 0 for total memory as output is invalid -" + result); } } // find the free memory. if (result.contains("MemFree") && result.split("\\s+").length > 2){ try { parsedResult = Long.parseLong(result.split("\\s+")[1]); logger.debug("Free memory : " + parsedResult); totalFreeMemory += parsedResult; }catch(NumberFormatException e){ logger.error("yielding 0 for free memory as output is invalid -" + result); } } // find the Buffers. if (result.contains("Buffers") && result.split("\\s+").length > 2){ try { parsedResult = Long.parseLong(result.split("\\s+")[1]); logger.debug("Buffers : " + parsedResult); totalFreeMemory += parsedResult; }catch(NumberFormatException e){ logger.error("yielding 0 for Buffers as output is invalid -" + result); } } // find the Cached. if (result.contains("Cached") && result.split("\\s+").length > 2){ try { parsedResult = Long.parseLong(result.split("\\s+")[1]); logger.debug("Cached : " + parsedResult); totalFreeMemory += parsedResult; }catch(NumberFormatException e){ logger.error("yielding 0 for Cached as output is invalid -" + result); } } // find the SwapCached. if (result.contains("SwapCached") && result.split("\\s+").length > 2){ try { parsedResult = Long.parseLong(result.split("\\s+")[1]); logger.debug("SwapCached : " + parsedResult); totalFreeMemory += parsedResult; }catch(NumberFormatException e){ logger.error("yielding 0 for SwapCached as output is invalid -" + result); } } } }else { logger.error("failed to get total/free memory info as the bash call returned invalid result."); } // the number got from the proc file is in KBs we want to see the number in MBs so we are dividing it by 1024. stats.setRemainingMemoryInMB(totalFreeMemory/1024); stats.setRemainingMemoryPercent(totalMemory == 0 ? 0 : ((double)totalFreeMemory / (double)totalMemory)*100); } catch (Exception ex){ logger.error("failed fetch system memory info " + "as exception is captured when fetching result from bash call. Ex -" + ex.getMessage()); } } else { logger.error("failed fetch system memory info, one or more files from the following list are missing - " + "'/bin/bash'," + "'/bin/cat'," +"'/proc/loadavg'"); } } /** * call the data providers to fill the returning data container for statistics data. * This function refreshes the static cached copy of data in case if necessary. * */ protected synchronized void populateStatistics(boolean noCache){ //check again before starting the work. if (noCache || System.currentTimeMillis() - lastRefreshedTime > cacheTimeInMilliseconds){ final ExecutorInfo stats = new ExecutorInfo(); fillRemainingMemoryPercent(stats); fillRemainingFlowCapacityAndLastDispatchedTime(stats); fillCpuUsage(stats); cachedstats = stats; lastRefreshedTime = System.currentTimeMillis(); } } /** * fill the result set with the remaining flow capacity . * @param stats reference to the result container which contains all the results, this specific method * will only work on the property "remainingFlowCapacity". */ protected void fillRemainingFlowCapacityAndLastDispatchedTime(ExecutorInfo stats){ AzkabanExecutorServer server = AzkabanExecutorServer.getApp(); if (server != null){ FlowRunnerManager runnerMgr = AzkabanExecutorServer.getApp().getFlowRunnerManager(); int assignedFlows = runnerMgr.getNumRunningFlows() + runnerMgr.getNumQueuedFlows(); stats.setRemainingFlowCapacity(runnerMgr.getMaxNumRunningFlows() - assignedFlows); stats.setNumberOfAssignedFlows(assignedFlows); stats.setLastDispatchedTime(runnerMgr.getLastFlowSubmittedTime()); }else { logger.error("failed to get data for remaining flow capacity or LastDispatchedTime" + " as the AzkabanExecutorServer has yet been initialized."); } } /**<pre> * fill the result set with the CPU usage . * Note : As the 'Top' bash call doesn't yield accurate result for the system load, * the implementation has been changed to load from the "proc/loadavg" which keeps * the moving average of the system load, we are pulling the average for the recent 1 min. *</pre> * @param stats reference to the result container which contains all the results, this specific method * will only work on the property "cpuUsage". */ protected void fillCpuUsage(ExecutorInfo stats){ if (new File("/bin/bash").exists() && new File("/bin/cat").exists() && new File("/proc/loadavg").exists()) { java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder("/bin/bash", "-c", "/bin/cat /proc/loadavg"); try { ArrayList<String> output = new ArrayList<String>(); Process process = processBuilder.start(); process.waitFor(); InputStream inputStream = process.getInputStream(); try { java.io.BufferedReader reader = new java.io.BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = reader.readLine()) != null) { output.add(line); } }finally { inputStream.close(); } // process the output from bash call. if (output.size() > 0) { String[] splitedresult = output.get(0).split("\\s+"); double cpuUsage = 0.0; try { cpuUsage = Double.parseDouble(splitedresult[0]); }catch(NumberFormatException e){ logger.error("yielding 0.0 for CPU usage as output is invalid -" + output.get(0)); } logger.info("System load : " + cpuUsage); stats.setCpuUpsage(cpuUsage); } } catch (Exception ex){ logger.error("failed fetch system load info " + "as exception is captured when fetching result from bash call. Ex -" + ex.getMessage()); } } else { logger.error("failed fetch system load info, one or more files from the following list are missing - " + "'/bin/bash'," + "'/bin/cat'," +"'/proc/loadavg'"); } } }
Remove the ristriction of the bash call returns as some of the system may miss couple of the memory categories.
azkaban-execserver/src/main/java/azkaban/execapp/ServerStatisticsServlet.java
Remove the ristriction of the bash call returns as some of the system may miss couple of the memory categories.
Java
apache-2.0
44615f6cb2d1ab3e7c2f7bac63ae1a76b290bc34
0
luyiisme/netty,mx657649013/netty,Techcable/netty,ngocdaothanh/netty,blucas/netty,mikkokar/netty,Apache9/netty,ichaki5748/netty,maliqq/netty,joansmith/netty,maliqq/netty,fenik17/netty,maliqq/netty,yrcourage/netty,mcobrien/netty,jchambers/netty,artgon/netty,idelpivnitskiy/netty,NiteshKant/netty,KatsuraKKKK/netty,idelpivnitskiy/netty,doom369/netty,NiteshKant/netty,ejona86/netty,fengjiachun/netty,doom369/netty,Squarespace/netty,blucas/netty,cnoldtree/netty,louxiu/netty,cnoldtree/netty,ichaki5748/netty,blucas/netty,carl-mastrangelo/netty,golovnin/netty,mcobrien/netty,mikkokar/netty,louxiu/netty,kiril-me/netty,yrcourage/netty,netty/netty,tbrooks8/netty,tbrooks8/netty,Apache9/netty,artgon/netty,bryce-anderson/netty,Scottmitch/netty,fenik17/netty,joansmith/netty,mcobrien/netty,johnou/netty,jongyeol/netty,gerdriesselmann/netty,NiteshKant/netty,KatsuraKKKK/netty,jchambers/netty,windie/netty,jongyeol/netty,Apache9/netty,Spikhalskiy/netty,ichaki5748/netty,idelpivnitskiy/netty,andsel/netty,SinaTadayon/netty,ngocdaothanh/netty,gerdriesselmann/netty,Scottmitch/netty,zer0se7en/netty,skyao/netty,KatsuraKKKK/netty,louxiu/netty,golovnin/netty,joansmith/netty,louxiu/netty,SinaTadayon/netty,mx657649013/netty,yrcourage/netty,gerdriesselmann/netty,Scottmitch/netty,netty/netty,Squarespace/netty,Spikhalskiy/netty,yrcourage/netty,SinaTadayon/netty,s-gheldd/netty,kiril-me/netty,ejona86/netty,maliqq/netty,bryce-anderson/netty,luyiisme/netty,zer0se7en/netty,Apache9/netty,golovnin/netty,doom369/netty,fengjiachun/netty,luyiisme/netty,kiril-me/netty,cnoldtree/netty,mikkokar/netty,tbrooks8/netty,Techcable/netty,windie/netty,skyao/netty,Squarespace/netty,windie/netty,s-gheldd/netty,mikkokar/netty,yrcourage/netty,golovnin/netty,louxiu/netty,Squarespace/netty,luyiisme/netty,zer0se7en/netty,carl-mastrangelo/netty,ejona86/netty,andsel/netty,joansmith/netty,skyao/netty,andsel/netty,johnou/netty,ngocdaothanh/netty,kiril-me/netty,jchambers/netty,zer0se7en/netty,tbrooks8/netty,joansmith/netty,s-gheldd/netty,NiteshKant/netty,KatsuraKKKK/netty,skyao/netty,jongyeol/netty,carl-mastrangelo/netty,ejona86/netty,doom369/netty,fengjiachun/netty,Scottmitch/netty,johnou/netty,ichaki5748/netty,golovnin/netty,jchambers/netty,fengjiachun/netty,mikkokar/netty,fenik17/netty,artgon/netty,andsel/netty,blucas/netty,NiteshKant/netty,fenik17/netty,Spikhalskiy/netty,KatsuraKKKK/netty,s-gheldd/netty,tbrooks8/netty,ichaki5748/netty,ngocdaothanh/netty,blucas/netty,Techcable/netty,artgon/netty,johnou/netty,bryce-anderson/netty,SinaTadayon/netty,ngocdaothanh/netty,artgon/netty,kiril-me/netty,mcobrien/netty,gerdriesselmann/netty,Spikhalskiy/netty,jchambers/netty,jongyeol/netty,carl-mastrangelo/netty,skyao/netty,mx657649013/netty,mx657649013/netty,gerdriesselmann/netty,bryce-anderson/netty,mx657649013/netty,fenik17/netty,Techcable/netty,SinaTadayon/netty,doom369/netty,mcobrien/netty,luyiisme/netty,bryce-anderson/netty,carl-mastrangelo/netty,Scottmitch/netty,Apache9/netty,zer0se7en/netty,jongyeol/netty,idelpivnitskiy/netty,maliqq/netty,windie/netty,andsel/netty,Techcable/netty,netty/netty,cnoldtree/netty,johnou/netty,windie/netty,ejona86/netty,netty/netty,Spikhalskiy/netty,cnoldtree/netty,fengjiachun/netty,Squarespace/netty,s-gheldd/netty,netty/netty,idelpivnitskiy/netty
/* * Copyright 2014 The Netty Project * * The Netty 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 io.netty.handler.codec.http2; import static io.netty.util.internal.ObjectUtil.checkNotNull; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerAdapter; import io.netty.util.internal.logging.InternalLogLevel; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; /** * Logs HTTP2 frames for debugging purposes. */ public class Http2FrameLogger extends ChannelHandlerAdapter { public enum Direction { INBOUND, OUTBOUND } private static final int BUFFER_LENGTH_THRESHOLD = 64; private final InternalLogger logger; private final InternalLogLevel level; public Http2FrameLogger(InternalLogLevel level) { this(level, InternalLoggerFactory.getInstance(Http2FrameLogger.class)); } public Http2FrameLogger(InternalLogLevel level, InternalLogger logger) { this.level = checkNotNull(level, "level"); this.logger = checkNotNull(logger, "logger"); } public void logData(Direction direction, int streamId, ByteBuf data, int padding, boolean endStream) { if (enabled()) { log(direction, "DATA: streamId=%d, padding=%d, endStream=%b, length=%d, bytes=%s", streamId, padding, endStream, data.readableBytes(), toString(data)); } } public void logHeaders(Direction direction, int streamId, Http2Headers headers, int padding, boolean endStream) { if (enabled()) { log(direction, "HEADERS: streamId:%d, headers=%s, padding=%d, endStream=%b", streamId, headers, padding, endStream); } } public void logHeaders(Direction direction, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) { if (enabled()) { log(direction, "HEADERS: streamId:%d, headers=%s, streamDependency=%d, weight=%d, exclusive=%b, " + "padding=%d, endStream=%b", streamId, headers, streamDependency, weight, exclusive, padding, endStream); } } public void logPriority(Direction direction, int streamId, int streamDependency, short weight, boolean exclusive) { if (enabled()) { log(direction, "PRIORITY: streamId=%d, streamDependency=%d, weight=%d, exclusive=%b", streamId, streamDependency, weight, exclusive); } } public void logRstStream(Direction direction, int streamId, long errorCode) { if (enabled()) { log(direction, "RST_STREAM: streamId=%d, errorCode=%d", streamId, errorCode); } } public void logSettingsAck(Direction direction) { if (enabled()) { log(direction, "SETTINGS ack=true"); } } public void logSettings(Direction direction, Http2Settings settings) { if (enabled()) { log(direction, "SETTINGS: ack=false, settings=%s", settings); } } public void logPing(Direction direction, ByteBuf data) { if (enabled()) { log(direction, "PING: ack=false, length=%d, bytes=%s", data.readableBytes(), toString(data)); } } public void logPingAck(Direction direction, ByteBuf data) { if (enabled()) { log(direction, "PING: ack=true, length=%d, bytes=%s", data.readableBytes(), toString(data)); } } public void logPushPromise(Direction direction, int streamId, int promisedStreamId, Http2Headers headers, int padding) { if (enabled()) { log(direction, "PUSH_PROMISE: streamId=%d, promisedStreamId=%d, headers=%s, padding=%d", streamId, promisedStreamId, headers, padding); } } public void logGoAway(Direction direction, int lastStreamId, long errorCode, ByteBuf debugData) { if (enabled()) { log(direction, "GO_AWAY: lastStreamId=%d, errorCode=%d, length=%d, bytes=%s", lastStreamId, errorCode, debugData.readableBytes(), toString(debugData)); } } public void logWindowsUpdate(Direction direction, int streamId, int windowSizeIncrement) { if (enabled()) { log(direction, "WINDOW_UPDATE: streamId=%d, windowSizeIncrement=%d", streamId, windowSizeIncrement); } } public void logUnknownFrame(Direction direction, byte frameType, int streamId, Http2Flags flags, ByteBuf data) { if (enabled()) { log(direction, "UNKNOWN: frameType=%d, streamId=%d, flags=%d, length=%d, bytes=%s", frameType & 0xFF, streamId, flags.value(), data.readableBytes(), toString(data)); } } private boolean enabled() { return logger.isEnabled(level); } private String toString(ByteBuf buf) { if (level == InternalLogLevel.TRACE || buf.readableBytes() <= BUFFER_LENGTH_THRESHOLD) { // Log the entire buffer. return ByteBufUtil.hexDump(buf); } // Otherwise just log the first 64 bytes. int length = Math.min(buf.readableBytes(), BUFFER_LENGTH_THRESHOLD); return ByteBufUtil.hexDump(buf, buf.readerIndex(), length) + "..."; } private void log(Direction direction, String format, Object... args) { StringBuilder b = new StringBuilder(200); b.append("\n----------------") .append(direction.name()) .append("--------------------\n") .append(String.format(format, args)) .append("\n------------------------------------"); logger.log(level, b.toString()); } }
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameLogger.java
/* * Copyright 2014 The Netty Project * * The Netty 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 io.netty.handler.codec.http2; import static io.netty.util.internal.ObjectUtil.checkNotNull; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerAdapter; import io.netty.util.internal.logging.InternalLogLevel; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; /** * Logs HTTP2 frames for debugging purposes. */ public class Http2FrameLogger extends ChannelHandlerAdapter { public enum Direction { INBOUND, OUTBOUND } private final InternalLogger logger; private final InternalLogLevel level; public Http2FrameLogger(InternalLogLevel level) { this(level, InternalLoggerFactory.getInstance(Http2FrameLogger.class)); } public Http2FrameLogger(InternalLogLevel level, InternalLogger logger) { this.level = checkNotNull(level, "level"); this.logger = checkNotNull(logger, "logger"); } public void logData(Direction direction, int streamId, ByteBuf data, int padding, boolean endStream) { log(direction, "DATA: streamId=%d, padding=%d, endStream=%b, length=%d, bytes=%s", streamId, padding, endStream, data.readableBytes(), ByteBufUtil.hexDump(data)); } public void logHeaders(Direction direction, int streamId, Http2Headers headers, int padding, boolean endStream) { log(direction, "HEADERS: streamId:%d, headers=%s, padding=%d, endStream=%b", streamId, headers, padding, endStream); } public void logHeaders(Direction direction, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) { log(direction, "HEADERS: streamId:%d, headers=%s, streamDependency=%d, weight=%d, exclusive=%b, " + "padding=%d, endStream=%b", streamId, headers, streamDependency, weight, exclusive, padding, endStream); } public void logPriority(Direction direction, int streamId, int streamDependency, short weight, boolean exclusive) { log(direction, "PRIORITY: streamId=%d, streamDependency=%d, weight=%d, exclusive=%b", streamId, streamDependency, weight, exclusive); } public void logRstStream(Direction direction, int streamId, long errorCode) { log(direction, "RST_STREAM: streamId=%d, errorCode=%d", streamId, errorCode); } public void logSettingsAck(Direction direction) { log(direction, "SETTINGS ack=true"); } public void logSettings(Direction direction, Http2Settings settings) { log(direction, "SETTINGS: ack=false, settings=%s", settings); } public void logPing(Direction direction, ByteBuf data) { log(direction, "PING: ack=false, length=%d, bytes=%s", data.readableBytes(), ByteBufUtil.hexDump(data)); } public void logPingAck(Direction direction, ByteBuf data) { log(direction, "PING: ack=true, length=%d, bytes=%s", data.readableBytes(), ByteBufUtil.hexDump(data)); } public void logPushPromise(Direction direction, int streamId, int promisedStreamId, Http2Headers headers, int padding) { log(direction, "PUSH_PROMISE: streamId=%d, promisedStreamId=%d, headers=%s, padding=%d", streamId, promisedStreamId, headers, padding); } public void logGoAway(Direction direction, int lastStreamId, long errorCode, ByteBuf debugData) { log(direction, "GO_AWAY: lastStreamId=%d, errorCode=%d, length=%d, bytes=%s", lastStreamId, errorCode, debugData.readableBytes(), ByteBufUtil.hexDump(debugData)); } public void logWindowsUpdate(Direction direction, int streamId, int windowSizeIncrement) { log(direction, "WINDOW_UPDATE: streamId=%d, windowSizeIncrement=%d", streamId, windowSizeIncrement); } public void logUnknownFrame(Direction direction, byte frameType, int streamId, Http2Flags flags, ByteBuf data) { log(direction, "UNKNOWN: frameType=%d, streamId=%d, flags=%d, length=%d, bytes=%s", frameType & 0xFF, streamId, flags.value(), data.readableBytes(), ByteBufUtil.hexDump(data)); } private void log(Direction direction, String format, Object... args) { if (logger.isEnabled(level)) { StringBuilder b = new StringBuilder(200); b.append("\n----------------") .append(direction.name()) .append("--------------------\n") .append(String.format(format, args)) .append("\n------------------------------------"); logger.log(level, b.toString()); } } }
Optimizations for Http2FrameLogger Motivation: The logger was always performing a hex dump of the ByteBufs regarless whether or not the log would take place. Modifications: Fixed the logger to avoid serializing the ByteBufs and calling the varargs method if logging is not enabled. Result: The loggers should run MUCH faster when disabled.
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameLogger.java
Optimizations for Http2FrameLogger
Java
apache-2.0
1085fa11b4a50dff56af90e1b23dd37d0460d859
0
apache/ode,Subasinghe/ode,mproch/apache-ode,apache/ode,mproch/apache-ode,Subasinghe/ode,Subasinghe/ode,Subasinghe/ode,apache/ode,Subasinghe/ode,apache/ode,apache/ode
package org.apache.ode.bpel.engine.migration; import org.apache.ode.bpel.engine.Contexts; import org.apache.ode.bpel.engine.BpelDatabase; import org.apache.ode.bpel.engine.BpelProcess; import org.apache.ode.bpel.dao.BpelDAOConnection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.sql.*; import java.util.*; import java.util.concurrent.Callable; /** * Checks database schema versions and migrates when necessary. */ public class MigrationHandler { private static final Log __log = LogFactory.getLog(MigrationHandler.class); public static final int CURRENT_SCHEMA_VERSION = 3; private Contexts _contexts; private List<Object[]> migrations = new ArrayList<Object[]>() {{ add(new Object[] { 2, new CorrelatorsMigration() }); add(new Object[] { 2, new CorrelationKeyMigration() }); add(new Object[] { 3, new CorrelationKeySetMigration() }); }}; public MigrationHandler(Contexts _contexts) { this._contexts = _contexts; } public boolean migrate(final Set<BpelProcess> registeredProcesses) { if (_contexts.dao.getDataSource() == null) { __log.debug("No datasource available, stopping migration. Probably running fully in-memory."); return false; } final int version; try { version = getDbVersion(); } catch (Throwable e) { __log.info("The ODE_SCHEMA_VERSION database table doesn't exist. Unless you need to migrate your data" + "from a past version, this message can be safely ignored."); return false; } if (version == -1) { __log.info("No schema version available from the database, migrations will be skipped."); return false; } try { boolean success = _contexts.scheduler.execTransaction(new Callable<Boolean>() { public Boolean call() throws Exception { boolean res = true; boolean migrated = false; for (Object[] me : migrations) { if (((Integer)me[0]) > version) { __log.debug("Running migration " + me[1]); res = ((Migration)me[1]).migrate(registeredProcesses, _contexts.dao.getConnection()) && res; migrated = true; } } if (!res) _contexts.scheduler.setRollbackOnly(); else if (migrated) setDbVersion(CURRENT_SCHEMA_VERSION); return res; } }); return success; } catch (Exception e) { __log.error("An error occured while migrating your database to a newer version of ODE, changes have " + "been aborted", e); throw new RuntimeException(e); } } private int getDbVersion() { int version = -1; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = _contexts.dao.getDataSource().getConnection(); stmt = conn.prepareStatement("SELECT VERSION FROM ODE_SCHEMA_VERSION"); rs = stmt.executeQuery(); if (rs.next()) version = rs.getInt("VERSION"); } catch (Exception e) { // Swallow, we'll just abort based on the version number } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } return version; } private void setDbVersion(int version) { Connection conn = null; Statement stmt = null; try { conn = _contexts.dao.getDataSource().getConnection(); stmt = conn.createStatement(); int res = stmt.executeUpdate("UPDATE ODE_SCHEMA_VERSION SET VERSION = " + version); // This should never happen but who knows? if (res == 0) throw new RuntimeException("Couldn't update schema version."); } catch (Exception e) { // Swallow, we'll just abort based on the version number } finally { try { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } }
bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/MigrationHandler.java
package org.apache.ode.bpel.engine.migration; import org.apache.ode.bpel.engine.Contexts; import org.apache.ode.bpel.engine.BpelDatabase; import org.apache.ode.bpel.engine.BpelProcess; import org.apache.ode.bpel.dao.BpelDAOConnection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.sql.*; import java.util.*; import java.util.concurrent.Callable; /** * Checks database schema versions and migrates when necessary. */ public class MigrationHandler { private static final Log __log = LogFactory.getLog(MigrationHandler.class); public static final int CURRENT_SCHEMA_VERSION = 3; private Contexts _contexts; private List<Object[]> migrations = new ArrayList<Object[]>() {{ add(new Object[] { 2, new CorrelatorsMigration() }); add(new Object[] { 2, new CorrelationKeyMigration() }); add(new Object[] { 3, new CorrelationKeySetMigration() }); }}; public MigrationHandler(Contexts _contexts) { this._contexts = _contexts; } public boolean migrate(final Set<BpelProcess> registeredProcesses) { if (_contexts.dao.getDataSource() == null) { __log.debug("No datasource available, stopping migration. Probably running fully in-memory."); return false; } final int version; try { version = getDbVersion(); } catch (Exception e) { __log.info("The ODE_SCHEMA_VERSION database table doesn't exist. Unless you need to migrate your data" + "from a past version, this message can be safely ignored."); return false; } if (version == -1) { __log.info("No schema version available from the database, migrations will be skipped."); return false; } try { boolean success = _contexts.scheduler.execTransaction(new Callable<Boolean>() { public Boolean call() throws Exception { boolean res = true; boolean migrated = false; for (Object[] me : migrations) { if (((Integer)me[0]) > version) { __log.debug("Running migration " + me[1]); res = ((Migration)me[1]).migrate(registeredProcesses, _contexts.dao.getConnection()) && res; migrated = true; } } if (!res) _contexts.scheduler.setRollbackOnly(); else if (migrated) setDbVersion(CURRENT_SCHEMA_VERSION); return res; } }); return success; } catch (Exception e) { __log.error("An error occured while migrating your database to a newer version of ODE, changes have " + "been aborted", e); throw new RuntimeException(e); } } private int getDbVersion() { int version = -1; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = _contexts.dao.getDataSource().getConnection(); stmt = conn.prepareStatement("SELECT VERSION FROM ODE_SCHEMA_VERSION"); rs = stmt.executeQuery(); if (rs.next()) version = rs.getInt("VERSION"); } catch (Exception e) { // Swallow, we'll just abort based on the version number } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } return version; } private void setDbVersion(int version) { Connection conn = null; Statement stmt = null; try { conn = _contexts.dao.getDataSource().getConnection(); stmt = conn.createStatement(); int res = stmt.executeUpdate("UPDATE ODE_SCHEMA_VERSION SET VERSION = " + version); // This should never happen but who knows? if (res == 0) throw new RuntimeException("Couldn't update schema version."); } catch (Exception e) { // Swallow, we'll just abort based on the version number } finally { try { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } }
F***ing errors. git-svn-id: ed2a38fae5041245b5d023935edc1ed9538a260e@732894 13f79535-47bb-0310-9956-ffa450edef68
bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/MigrationHandler.java
F***ing errors.
Java
apache-2.0
325fbf931ce6cdb0f3c8951cc441a686b2c00ccf
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.actions; import com.intellij.execution.*; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.UnknownConfigurationType; import com.intellij.execution.impl.*; import com.intellij.execution.runners.ExecutionUtil; import com.intellij.execution.runners.ProgramRunner; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.macro.MacroManager; import com.intellij.ide.util.PropertiesComponent; import com.intellij.idea.ActionsBundle; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.ListPopupStep; import com.intellij.openapi.ui.popup.ListSeparator; import com.intellij.openapi.ui.popup.PopupStep; import com.intellij.openapi.ui.popup.util.BaseListPopupStep; import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.popup.WizardPopup; import com.intellij.ui.popup.list.ListPopupImpl; import com.intellij.ui.popup.list.PopupListElementRenderer; import com.intellij.ui.speedSearch.SpeedSearch; import com.intellij.util.ObjectUtils; import com.intellij.util.SmartList; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.util.List; import java.util.*; public class ChooseRunConfigurationPopup implements ExecutorProvider { private final Project myProject; @NotNull private final String myAddKey; @NotNull private final Executor myDefaultExecutor; @Nullable private final Executor myAlternativeExecutor; private Executor myCurrentExecutor; private boolean myEditConfiguration; private final RunListPopup myPopup; public ChooseRunConfigurationPopup(@NotNull Project project, @NotNull String addKey, @NotNull Executor defaultExecutor, @Nullable Executor alternativeExecutor) { myProject = project; myAddKey = addKey; myDefaultExecutor = defaultExecutor; myAlternativeExecutor = alternativeExecutor; myPopup = new RunListPopup(new ConfigurationListPopupStep(this, myProject, this, myDefaultExecutor.getActionName())); } public void show() { final String adText = getAdText(myAlternativeExecutor); if (adText != null) { myPopup.setAdText(adText); } myPopup.showCenteredInCurrentWindow(myProject); } protected static boolean canRun(@NotNull final Executor executor, final RunnerAndConfigurationSettings settings) { return ProgramRunnerUtil.getRunner(executor.getId(), settings) != null; } @Nullable protected String getAdText(final Executor alternateExecutor) { final PropertiesComponent properties = PropertiesComponent.getInstance(); if (alternateExecutor != null && !properties.isTrueValue(myAddKey)) { return String .format("Hold %s to %s", KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke("SHIFT")), alternateExecutor.getActionName()); } if (!properties.isTrueValue("run.configuration.edit.ad")) { return String.format("Press %s to Edit", KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke("F4"))); } if (!properties.isTrueValue("run.configuration.delete.ad")) { return String.format("Press %s to Delete configuration", KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke("DELETE"))); } return null; } private void registerActions(final RunListPopup popup) { popup.registerAction("alternateExecutor", KeyStroke.getKeyStroke("shift pressed SHIFT"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { myCurrentExecutor = myAlternativeExecutor; updatePresentation(); } }); popup.registerAction("restoreDefaultExecutor", KeyStroke.getKeyStroke("released SHIFT"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { myCurrentExecutor = myDefaultExecutor; updatePresentation(); } }); popup.registerAction("invokeAction", KeyStroke.getKeyStroke("shift ENTER"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { popup.handleSelect(true); } }); popup.registerAction("editConfiguration", KeyStroke.getKeyStroke("F4"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { myEditConfiguration = true; popup.handleSelect(true); } }); popup.registerAction("deleteConfiguration", KeyStroke.getKeyStroke("DELETE"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { popup.removeSelected(); } }); popup.registerAction("speedsearch_bksp", KeyStroke.getKeyStroke("BACK_SPACE"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { SpeedSearch speedSearch = popup.getSpeedSearch(); if (speedSearch.isHoldingFilter()) { speedSearch.backspace(); speedSearch.update(); } } }); for (int i = 0; i < 10; i++) { addNumberAction(popup, i); } } private void addNumberAction(RunListPopup popup, int number) { Action action = createNumberAction(number, popup, myDefaultExecutor); Action action_ = createNumberAction(number, popup, myAlternativeExecutor); popup.registerAction(number + "Action", KeyStroke.getKeyStroke(String.valueOf(number)), action); popup.registerAction(number + "Action_", KeyStroke.getKeyStroke("shift pressed " + number), action_); popup.registerAction(number + "Action1", KeyStroke.getKeyStroke("NUMPAD" + number), action); popup.registerAction(number + "Action_1", KeyStroke.getKeyStroke("shift pressed NUMPAD" + number), action_); } private void updatePresentation() { myPopup.setCaption(getExecutor().getActionName()); } static void execute(final ItemWrapper itemWrapper, final Executor executor) { if (executor == null) { return; } final DataContext dataContext = DataManager.getInstance().getDataContext(); final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null) { itemWrapper.perform(project, executor, dataContext); } } void editConfiguration(@NotNull Project project, @NotNull RunnerAndConfigurationSettings configuration) { final Executor executor = getExecutor(); PropertiesComponent.getInstance().setValue("run.configuration.edit.ad", Boolean.toString(true)); if (RunDialog.editConfiguration(project, configuration, "Edit configuration settings", executor)) { RunManager.getInstance(project).setSelectedConfiguration(configuration); ExecutionUtil.runConfiguration(configuration, executor); } } private static void deleteConfiguration(final Project project, @NotNull final RunnerAndConfigurationSettings configurationSettings) { if (Messages.YES == Messages.showYesNoDialog(project, "Are you sure you want to delete " + configurationSettings.getName() + "?", "Confirmation", Messages.getQuestionIcon())) { RunManager.getInstance(project).removeConfiguration(configurationSettings); } } @Override @NotNull public Executor getExecutor() { return myCurrentExecutor == null ? myDefaultExecutor : myCurrentExecutor; } private static Action createNumberAction(final int number, final ListPopupImpl listPopup, final Executor executor) { return new MyAbstractAction(listPopup, number, executor); } private abstract static class Wrapper { private int myMnemonic = -1; private final boolean myAddSeparatorAbove; private boolean myChecked; protected Wrapper(boolean addSeparatorAbove) { myAddSeparatorAbove = addSeparatorAbove; } public int getMnemonic() { return myMnemonic; } public boolean isChecked() { return myChecked; } public void setChecked(boolean checked) { myChecked = checked; } public void setMnemonic(int mnemonic) { myMnemonic = mnemonic; } public boolean addSeparatorAbove() { return myAddSeparatorAbove; } @Nullable public abstract Icon getIcon(); public abstract String getText(); public boolean canBeDeleted() { return false; } @Override public String toString() { return "Wrapper[" + getText() + "]"; } } public abstract static class ItemWrapper<T> extends Wrapper { private final T myValue; private boolean myDynamic; protected ItemWrapper(@Nullable final T value) { this(value, false); } protected ItemWrapper(@Nullable final T value, boolean addSeparatorAbove) { super(addSeparatorAbove); myValue = value; } public T getValue() { return myValue; } public boolean isDynamic() { return myDynamic; } public void setDynamic(final boolean b) { myDynamic = b; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ItemWrapper)) return false; ItemWrapper that = (ItemWrapper)o; if (myValue != null ? !myValue.equals(that.myValue) : that.myValue != null) return false; return true; } @Override public int hashCode() { return myValue != null ? myValue.hashCode() : 0; } public abstract void perform(@NotNull final Project project, @NotNull final Executor executor, @NotNull final DataContext context); @Nullable public ConfigurationType getType() { return null; } public boolean available(Executor executor) { return false; } public boolean hasActions() { return false; } public PopupStep getNextStep(Project project, ChooseRunConfigurationPopup action) { return PopupStep.FINAL_CHOICE; } public static ItemWrapper wrap(@NotNull final Project project, @NotNull final RunnerAndConfigurationSettings settings, final boolean dynamic) { final ItemWrapper result = wrap(project, settings); result.setDynamic(dynamic); return result; } public static ItemWrapper wrap(@NotNull final Project project, @NotNull final RunnerAndConfigurationSettings settings) { return new ItemWrapper<RunnerAndConfigurationSettings>(settings) { @Override public void perform(@NotNull Project project, @NotNull Executor executor, @NotNull DataContext context) { RunnerAndConfigurationSettings config = getValue(); RunManager.getInstance(project).setSelectedConfiguration(config); MacroManager.getInstance().cacheMacrosPreview(context); ExecutionUtil.runConfiguration(config, executor); } @Override public ConfigurationType getType() { return getValue().getType(); } @Override public Icon getIcon() { return RunManagerEx.getInstanceEx(project).getConfigurationIcon(getValue(), true); } @Override public String getText() { return Executor.shortenNameIfNeed(getValue().getName()) + getValue().getConfiguration().getPresentableType(); } @Override public boolean hasActions() { return true; } @Override public boolean available(Executor executor) { return ProgramRunnerUtil.getRunner(executor.getId(), getValue()) != null; } @Override public PopupStep getNextStep(@NotNull final Project project, @NotNull final ChooseRunConfigurationPopup action) { return new ConfigurationActionsStep(project, action, getValue(), isDynamic()); } }; } @Override public boolean canBeDeleted() { return !isDynamic() && getValue() instanceof RunnerAndConfigurationSettings; } } private static final class ConfigurationListPopupStep extends BaseListPopupStep<ItemWrapper> { private final Project myProject; private final ChooseRunConfigurationPopup myAction; private int myDefaultConfiguration = -1; private ConfigurationListPopupStep(@NotNull final ChooseRunConfigurationPopup action, @NotNull final Project project, @NotNull final ExecutorProvider executorProvider, @NotNull final String title) { super(title, createSettingsList(project, executorProvider, true)); myProject = project; myAction = action; if (-1 == getDefaultOptionIndex()) { myDefaultConfiguration = getDynamicIndex(); } } private int getDynamicIndex() { int i = 0; for (final ItemWrapper wrapper : getValues()) { if (wrapper.isDynamic()) { return i; } i++; } return -1; } @Override public boolean isAutoSelectionEnabled() { return false; } @Override public ListSeparator getSeparatorAbove(ItemWrapper value) { if (value.addSeparatorAbove()) return new ListSeparator(); final List<ItemWrapper> configurations = getValues(); final int index = configurations.indexOf(value); if (index > 0 && index <= configurations.size() - 1) { final ItemWrapper aboveConfiguration = configurations.get(index - 1); if (aboveConfiguration != null && aboveConfiguration.isDynamic() != value.isDynamic()) { return new ListSeparator(); } final ConfigurationType currentType = value.getType(); final ConfigurationType aboveType = aboveConfiguration == null ? null : aboveConfiguration.getType(); if (aboveType != currentType && currentType != null) { return new ListSeparator(); // new ListSeparator(currentType.getDisplayName()); } } return null; } @Override public boolean isSpeedSearchEnabled() { return true; } @Override public int getDefaultOptionIndex() { final RunnerAndConfigurationSettings currentConfiguration = RunManager.getInstance(myProject).getSelectedConfiguration(); if (currentConfiguration == null && myDefaultConfiguration != -1) { return myDefaultConfiguration; } return currentConfiguration instanceof RunnerAndConfigurationSettingsImpl ? getValues() .indexOf(ItemWrapper.wrap(myProject, currentConfiguration)) : -1; } @Override public PopupStep onChosen(final ItemWrapper wrapper, boolean finalChoice) { if (myAction.myEditConfiguration) { final Object o = wrapper.getValue(); if (o instanceof RunnerAndConfigurationSettingsImpl) { return doFinalStep(() -> myAction.editConfiguration(myProject, (RunnerAndConfigurationSettings)o)); } } if (finalChoice && wrapper.available(myAction.getExecutor())) { return doFinalStep(() -> { if (myAction.getExecutor() == myAction.myAlternativeExecutor) { PropertiesComponent.getInstance().setValue(myAction.myAddKey, Boolean.toString(true)); } wrapper.perform(myProject, myAction.getExecutor(), DataManager.getInstance().getDataContext()); }); } else { return wrapper.getNextStep(myProject, myAction); } } @Override public boolean hasSubstep(ItemWrapper selectedValue) { return selectedValue.hasActions(); } @NotNull @Override public String getTextFor(ItemWrapper value) { return value.getText(); } @Override public Icon getIconFor(ItemWrapper value) { return value.getIcon(); } } private static final class ConfigurationActionsStep extends BaseListPopupStep<ActionWrapper> { @NotNull private final RunnerAndConfigurationSettings mySettings; @NotNull private final Project myProject; private ConfigurationActionsStep(@NotNull final Project project, ChooseRunConfigurationPopup action, @NotNull final RunnerAndConfigurationSettings settings, final boolean dynamic) { super(null, buildActions(project, action, settings, dynamic)); myProject = project; mySettings = settings; } @NotNull public RunnerAndConfigurationSettings getSettings() { return mySettings; } public String getName() { return Executor.shortenNameIfNeed(mySettings.getName()); } public Icon getIcon() { return RunManagerEx.getInstanceEx(myProject).getConfigurationIcon(mySettings); } @Override public ListSeparator getSeparatorAbove(ActionWrapper value) { return value.addSeparatorAbove() ? new ListSeparator() : null; } private static ActionWrapper[] buildActions(@NotNull final Project project, final ChooseRunConfigurationPopup action, @NotNull final RunnerAndConfigurationSettings settings, final boolean dynamic) { final List<ActionWrapper> result = new ArrayList<>(); final ExecutionTarget active = ExecutionTargetManager.getActiveTarget(project); for (final ExecutionTarget eachTarget : ExecutionTargetManager.getTargetsToChooseFor(project, settings.getConfiguration())) { result.add(new ActionWrapper(eachTarget.getDisplayName(), eachTarget.getIcon()) { { setChecked(eachTarget.equals(active)); } @Override public void perform() { final RunManager manager = RunManager.getInstance(project); if (dynamic) { manager.setTemporaryConfiguration(settings); } manager.setSelectedConfiguration(settings); ExecutionTargetManager.setActiveTarget(project, eachTarget); ExecutionUtil.runConfiguration(settings, action.getExecutor()); } }); } boolean isFirst = true; for (final Executor executor : ExecutorRegistry.getInstance().getRegisteredExecutors()) { final ProgramRunner runner = ProgramRunner.getRunner(executor.getId(), settings.getConfiguration()); if (runner != null) { result.add(new ActionWrapper(executor.getActionName(), executor.getIcon(), isFirst) { @Override public void perform() { final RunManager manager = RunManager.getInstance(project); if (dynamic) { manager.setTemporaryConfiguration(settings); } manager.setSelectedConfiguration(settings); ExecutionUtil.runConfiguration(settings, executor); } }); isFirst = false; } } result.add(new ActionWrapper("Edit...", AllIcons.Actions.EditSource, true) { @Override public void perform() { if (dynamic) { RunManager.getInstance(project).setTemporaryConfiguration(settings); } action.editConfiguration(project, settings); } }); if (settings.isTemporary() || dynamic) { result.add(new ActionWrapper("Save configuration", AllIcons.Actions.Menu_saveall) { @Override public void perform() { final RunManager manager = RunManager.getInstance(project); if (dynamic) { manager.setTemporaryConfiguration(settings); } manager.makeStable(settings); } }); } result.add(new ActionWrapper("Delete", AllIcons.Actions.Cancel) { @Override public void perform() { deleteConfiguration(project, settings); } }); return result.toArray(new ActionWrapper[0]); } @Override public PopupStep onChosen(final ActionWrapper selectedValue, boolean finalChoice) { return doFinalStep(() -> selectedValue.perform()); } @Override public Icon getIconFor(ActionWrapper aValue) { return aValue.getIcon(); } @NotNull @Override public String getTextFor(ActionWrapper value) { return value.getText(); } } private abstract static class ActionWrapper extends Wrapper { private final String myName; private final Icon myIcon; private ActionWrapper(String name, Icon icon) { this(name, icon, false); } private ActionWrapper(String name, Icon icon, boolean addSeparatorAbove) { super(addSeparatorAbove); myName = name; myIcon = icon; } public abstract void perform(); @Override public String getText() { return myName; } @Override public Icon getIcon() { return myIcon; } } private static class RunListElementRenderer extends PopupListElementRenderer { private JLabel myLabel; private final ListPopupImpl myPopup1; private final boolean myHasSideBar; private RunListElementRenderer(ListPopupImpl popup, boolean hasSideBar) { super(popup); myPopup1 = popup; myHasSideBar = hasSideBar; } @Override protected JComponent createItemComponent() { if (myLabel == null) { myLabel = new JLabel(); myLabel.setPreferredSize(new JLabel("8.").getPreferredSize()); } final JComponent result = super.createItemComponent(); result.add(myLabel, BorderLayout.WEST); return result; } @Override protected void customizeComponent(JList list, Object value, boolean isSelected) { super.customizeComponent(list, value, isSelected); myLabel.setVisible(myHasSideBar); ListPopupStep<Object> step = myPopup1.getListStep(); boolean isSelectable = step.isSelectable(value); myLabel.setEnabled(isSelectable); myLabel.setIcon(null); if (isSelected) { setSelected(myLabel); } else { setDeselected(myLabel); } if (value instanceof Wrapper) { Wrapper wrapper = (Wrapper)value; final int mnemonic = wrapper.getMnemonic(); if (mnemonic != -1 && !myPopup1.getSpeedSearch().isHoldingFilter()) { myLabel.setText(mnemonic + "."); myLabel.setDisplayedMnemonicIndex(0); } else { if (wrapper.isChecked()) { myTextLabel.setIcon(isSelected ? RunConfigurationsComboBoxAction.CHECKED_SELECTED_ICON : RunConfigurationsComboBoxAction.CHECKED_ICON); } else { if (myTextLabel.getIcon() == null) { myTextLabel.setIcon(RunConfigurationsComboBoxAction.EMPTY_ICON); } } myLabel.setText(""); } } } } private static class MyAbstractAction extends AbstractAction implements DumbAware { private final ListPopupImpl myListPopup; private final int myNumber; private final Executor myExecutor; MyAbstractAction(ListPopupImpl listPopup, int number, Executor executor) { myListPopup = listPopup; myNumber = number; myExecutor = executor; } @Override public void actionPerformed(ActionEvent e) { if (myListPopup.getSpeedSearch().isHoldingFilter()) return; for (final Object item : myListPopup.getListStep().getValues()) { if (item instanceof ItemWrapper && ((ItemWrapper)item).getMnemonic() == myNumber) { myListPopup.setFinalRunnable(() -> execute((ItemWrapper)item, myExecutor)); myListPopup.closeOk(null); } } } } private class RunListPopup extends ListPopupImpl { RunListPopup(ListPopupStep step) { super(step); registerActions(this); } protected RunListPopup(WizardPopup aParent, ListPopupStep aStep, Object parentValue) { super(aParent, aStep, parentValue); registerActions(this); } @Override protected WizardPopup createPopup(WizardPopup parent, PopupStep step, Object parentValue) { return new RunListPopup(parent, (ListPopupStep)step, parentValue); } @Override public void handleSelect(boolean handleFinalChoices, InputEvent e) { if (e instanceof MouseEvent && e.isShiftDown()) { handleShiftClick(handleFinalChoices, e, this); return; } _handleSelect(handleFinalChoices, e); } private void _handleSelect(boolean handleFinalChoices, InputEvent e) { super.handleSelect(handleFinalChoices, e); } protected void handleShiftClick(boolean handleFinalChoices, final InputEvent inputEvent, final RunListPopup popup) { myCurrentExecutor = myAlternativeExecutor; popup._handleSelect(handleFinalChoices, inputEvent); } @Override protected ListCellRenderer getListElementRenderer() { boolean hasSideBar = false; for (Object each : getListStep().getValues()) { if (each instanceof Wrapper) { if (((Wrapper)each).getMnemonic() != -1) { hasSideBar = true; break; } } } return new RunListElementRenderer(this, hasSideBar); } public void removeSelected() { final PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); if (!propertiesComponent.isTrueValue("run.configuration.delete.ad")) { propertiesComponent.setValue("run.configuration.delete.ad", Boolean.toString(true)); } final int index = getSelectedIndex(); if (index == -1) { return; } final Object o = getListModel().get(index); if (o instanceof ItemWrapper && ((ItemWrapper)o).canBeDeleted()) { deleteConfiguration(myProject, (RunnerAndConfigurationSettings)((ItemWrapper)o).getValue()); getListModel().deleteItem(o); final List<Object> values = getListStep().getValues(); values.remove(o); if (index < values.size()) { onChildSelectedFor(values.get(index)); } else if (index - 1 >= 0) { onChildSelectedFor(values.get(index - 1)); } } } @Override protected boolean isResizable() { return true; } } private static class FolderWrapper extends ItemWrapper<String> { private final Project myProject; private final ExecutorProvider myExecutorProvider; private final List<RunnerAndConfigurationSettings> myConfigurations; private FolderWrapper(Project project, ExecutorProvider executorProvider, @Nullable String value, List<RunnerAndConfigurationSettings> configurations) { super(value); myProject = project; myExecutorProvider = executorProvider; myConfigurations = configurations; } @Override public void perform(@NotNull Project project, @NotNull Executor executor, @NotNull DataContext context) { RunManager runManager = RunManager.getInstance(project); RunnerAndConfigurationSettings selectedConfiguration = runManager.getSelectedConfiguration(); if (myConfigurations.contains(selectedConfiguration)) { runManager.setSelectedConfiguration(selectedConfiguration); ExecutionUtil.runConfiguration(selectedConfiguration, myExecutorProvider.getExecutor()); } } @Nullable @Override public Icon getIcon() { return AllIcons.Nodes.Folder; } @Override public String getText() { return getValue(); } @Nullable @Override public ConfigurationType getType() { return Registry.is("run.popup.move.folders.to.top") || myConfigurations.isEmpty() ? null : myConfigurations.get(0).getType(); } @Override public boolean hasActions() { return true; } @Override public PopupStep getNextStep(Project project, ChooseRunConfigurationPopup action) { List<ConfigurationActionsStep> steps = new ArrayList<>(); for (RunnerAndConfigurationSettings settings : myConfigurations) { steps.add(new ConfigurationActionsStep(project, action, settings, false)); } return new FolderStep(myProject, myExecutorProvider, null, steps, action); } } private static final class FolderStep extends BaseListPopupStep<ConfigurationActionsStep> { private final Project myProject; private final ChooseRunConfigurationPopup myPopup; private final ExecutorProvider myExecutorProvider; private FolderStep(Project project, ExecutorProvider executorProvider, String folderName, List<ConfigurationActionsStep> children, ChooseRunConfigurationPopup popup) { super(folderName, children, new ArrayList<>()); myProject = project; myExecutorProvider = executorProvider; myPopup = popup; } @Override public PopupStep onChosen(final ConfigurationActionsStep selectedValue, boolean finalChoice) { if (finalChoice) { if (myPopup.myEditConfiguration) { final RunnerAndConfigurationSettings settings = selectedValue.getSettings(); return doFinalStep(() -> myPopup.editConfiguration(myProject, settings)); } return doFinalStep(() -> { RunnerAndConfigurationSettings settings = selectedValue.getSettings(); RunManager.getInstance(myProject).setSelectedConfiguration(settings); ExecutionUtil.runConfiguration(settings, myExecutorProvider.getExecutor()); }); } else { return selectedValue; } } @Override public Icon getIconFor(ConfigurationActionsStep aValue) { return aValue.getIcon(); } @NotNull @Override public String getTextFor(ConfigurationActionsStep value) { return value.getName(); } @Override public boolean hasSubstep(ConfigurationActionsStep selectedValue) { return !selectedValue.getValues().isEmpty(); } } @NotNull public static List<ItemWrapper> createSettingsList(@NotNull Project project, @NotNull ExecutorProvider executorProvider, boolean isCreateEditAction) { List<ItemWrapper> result = new ArrayList<>(); if (isCreateEditAction) { result.add(createEditAction()); } final RunnerAndConfigurationSettings selectedConfiguration = RunManager.getInstance(project).getSelectedConfiguration(); if (selectedConfiguration != null) { addActionsForSelected(selectedConfiguration, project, result); } Map<RunnerAndConfigurationSettings, ItemWrapper> wrappedExisting = new LinkedHashMap<>(); List<FolderWrapper> folderWrappers = new SmartList<>(); for (Map<String, List<RunnerAndConfigurationSettings>> structure : RunManagerImpl.getInstanceImpl(project).getConfigurationsGroupedByTypeAndFolder(false).values()) { for (Map.Entry<String, List<RunnerAndConfigurationSettings>> entry : structure.entrySet()) { final String folderName = entry.getKey(); if (folderName != null) { boolean isSelected = entry.getValue().contains(selectedConfiguration); if (isSelected) { assert selectedConfiguration != null; } FolderWrapper folderWrapper = new FolderWrapper(project, executorProvider, folderName + (isSelected ? " (mnemonic is to \"" + selectedConfiguration.getName() + "\")" : ""), entry.getValue()); if (isSelected) { folderWrapper.setMnemonic(1); } folderWrappers.add(folderWrapper); } else { for (RunnerAndConfigurationSettings configuration : entry.getValue()) { final ItemWrapper wrapped = ItemWrapper.wrap(project, configuration); if (configuration == selectedConfiguration) { wrapped.setMnemonic(1); } wrappedExisting.put(configuration, wrapped); } } } } boolean moveFoldersToTop = Registry.is("run.popup.move.folders.to.top"); if (moveFoldersToTop) { result.addAll(folderWrappers); } if (!DumbService.isDumb(project)) { populateWithDynamicRunners(result, wrappedExisting, project, RunManagerEx.getInstanceEx(project), selectedConfiguration); } final int topIndex = result.size() - 1; result.addAll(wrappedExisting.values()); if (!moveFoldersToTop) { for (FolderWrapper folderWrapper : folderWrappers) { int bestIndex = topIndex; for (int index = topIndex; index < result.size(); index++) { bestIndex = index; ConfigurationType folderType = ObjectUtils.notNull(folderWrapper.getType(), UnknownConfigurationType.getInstance()); ItemWrapper item = result.get(index); ConfigurationType currentType = item.getType(); int m = currentType == null ? 1 : RunConfigurationListManagerHelperKt.compareTypesForUi(folderType, currentType); if (m < 0 || (m == 0 && !(item instanceof FolderWrapper))) { break; } } result.add(bestIndex, folderWrapper); } } return result; } private static void addActionsForSelected(@NotNull RunnerAndConfigurationSettings selectedConfiguration, @NotNull Project project, @NotNull List<ItemWrapper> result) { boolean isFirst = true; final ExecutionTarget activeTarget = ExecutionTargetManager.getActiveTarget(project); for (ExecutionTarget eachTarget : ExecutionTargetManager.getTargetsToChooseFor(project, selectedConfiguration.getConfiguration())) { ItemWrapper<ExecutionTarget> itemWrapper = new ItemWrapper<ExecutionTarget>(eachTarget, isFirst) { @Override public Icon getIcon() { return getValue().getIcon(); } @Override public String getText() { return getValue().getDisplayName(); } @Override public void perform(@NotNull final Project project, @NotNull final Executor executor, @NotNull DataContext context) { ExecutionTargetManager.setActiveTarget(project, getValue()); ExecutionUtil.runConfiguration(selectedConfiguration, executor); } @Override public boolean available(Executor executor) { return true; } }; itemWrapper.setChecked(eachTarget.equals(activeTarget)); result.add(itemWrapper); isFirst = false; } } @NotNull private static ItemWrapper<Void> createEditAction() { ItemWrapper<Void> result = new ItemWrapper<Void>(null) { @Override public Icon getIcon() { return AllIcons.Actions.EditSource; } @Override public String getText() { return UIUtil.removeMnemonic(ActionsBundle.message("action.editRunConfigurations.text")); } @Override public void perform(@NotNull final Project project, @NotNull final Executor executor, @NotNull DataContext context) { if (new EditConfigurationsDialog(project) { @Override protected void init() { setOKButtonText(executor.getStartActionText()); setOKButtonIcon(executor.getIcon()); myExecutor = executor; super.init(); } }.showAndGet()) { ApplicationManager.getApplication().invokeLater(() -> { RunnerAndConfigurationSettings configuration = RunManager.getInstance(project).getSelectedConfiguration(); if (configuration != null) { ExecutionUtil.runConfiguration(configuration, executor); } }, project.getDisposed()); } } @Override public boolean available(Executor executor) { return true; } }; result.setMnemonic(0); return result; } private static void populateWithDynamicRunners(final List<? super ItemWrapper> result, Map<RunnerAndConfigurationSettings, ItemWrapper> existing, final Project project, final RunManager manager, final RunnerAndConfigurationSettings selectedConfiguration) { if (!EventQueue.isDispatchThread()) { return; } final DataContext dataContext = DataManager.getInstance().getDataContext(); final ConfigurationContext context = ConfigurationContext.getFromContext(dataContext); final List<ConfigurationFromContext> producers = PreferredProducerFind.getConfigurationsFromContext(context.getLocation(), context, false); if (producers == null) return; Collections.sort(producers, ConfigurationFromContext.NAME_COMPARATOR); final RunnerAndConfigurationSettings[] preferred = {null}; int i = 2; // selectedConfiguration == null ? 1 : 2; for (final ConfigurationFromContext fromContext : producers) { final RunnerAndConfigurationSettings configuration = fromContext.getConfigurationSettings(); if (existing.keySet().contains(configuration)) { final ItemWrapper wrapper = existing.get(configuration); if (wrapper.getMnemonic() != 1) { wrapper.setMnemonic(i); i++; } } else { if (selectedConfiguration != null && configuration.equals(selectedConfiguration)) continue; if (preferred[0] == null) { preferred[0] = configuration; } //noinspection unchecked final ItemWrapper wrapper = new ItemWrapper(configuration) { @Override public Icon getIcon() { return RunManagerEx.getInstanceEx(project).getConfigurationIcon(configuration); } @Override public String getText() { return Executor.shortenNameIfNeed(configuration.getName()) + configuration.getConfiguration().getPresentableType(); } @Override public boolean available(Executor executor) { return canRun(executor, configuration); } @Override public void perform(@NotNull Project project, @NotNull Executor executor, @NotNull DataContext context) { manager.setTemporaryConfiguration(configuration); RunManager.getInstance(project).setSelectedConfiguration(configuration); ExecutionUtil.runConfiguration(configuration, executor); } @Override public PopupStep getNextStep(@NotNull final Project project, @NotNull final ChooseRunConfigurationPopup action) { return new ConfigurationActionsStep(project, action, configuration, isDynamic()); } @Override public boolean hasActions() { return true; } }; wrapper.setDynamic(true); wrapper.setMnemonic(i); result.add(wrapper); i++; } } } }
platform/lang-impl/src/com/intellij/execution/actions/ChooseRunConfigurationPopup.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.actions; import com.intellij.execution.*; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.UnknownConfigurationType; import com.intellij.execution.impl.*; import com.intellij.execution.runners.ExecutionUtil; import com.intellij.execution.runners.ProgramRunner; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.macro.MacroManager; import com.intellij.ide.util.PropertiesComponent; import com.intellij.idea.ActionsBundle; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.ListPopupStep; import com.intellij.openapi.ui.popup.ListSeparator; import com.intellij.openapi.ui.popup.PopupStep; import com.intellij.openapi.ui.popup.util.BaseListPopupStep; import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.popup.WizardPopup; import com.intellij.ui.popup.list.ListPopupImpl; import com.intellij.ui.popup.list.PopupListElementRenderer; import com.intellij.ui.speedSearch.SpeedSearch; import com.intellij.util.ObjectUtils; import com.intellij.util.SmartList; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.util.List; import java.util.*; public class ChooseRunConfigurationPopup implements ExecutorProvider { private final Project myProject; @NotNull private final String myAddKey; @NotNull private final Executor myDefaultExecutor; @Nullable private final Executor myAlternativeExecutor; private Executor myCurrentExecutor; private boolean myEditConfiguration; private final RunListPopup myPopup; public ChooseRunConfigurationPopup(@NotNull Project project, @NotNull String addKey, @NotNull Executor defaultExecutor, @Nullable Executor alternativeExecutor) { myProject = project; myAddKey = addKey; myDefaultExecutor = defaultExecutor; myAlternativeExecutor = alternativeExecutor; myPopup = new RunListPopup(new ConfigurationListPopupStep(this, myProject, this, myDefaultExecutor.getActionName())); } public void show() { final String adText = getAdText(myAlternativeExecutor); if (adText != null) { myPopup.setAdText(adText); } myPopup.showCenteredInCurrentWindow(myProject); } protected static boolean canRun(@NotNull final Executor executor, final RunnerAndConfigurationSettings settings) { return ProgramRunnerUtil.getRunner(executor.getId(), settings) != null; } @Nullable protected String getAdText(final Executor alternateExecutor) { final PropertiesComponent properties = PropertiesComponent.getInstance(); if (alternateExecutor != null && !properties.isTrueValue(myAddKey)) { return String .format("Hold %s to %s", KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke("SHIFT")), alternateExecutor.getActionName()); } if (!properties.isTrueValue("run.configuration.edit.ad")) { return String.format("Press %s to Edit", KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke("F4"))); } if (!properties.isTrueValue("run.configuration.delete.ad")) { return String.format("Press %s to Delete configuration", KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke("DELETE"))); } return null; } private void registerActions(final RunListPopup popup) { popup.registerAction("alternateExecutor", KeyStroke.getKeyStroke("shift pressed SHIFT"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { myCurrentExecutor = myAlternativeExecutor; updatePresentation(); } }); popup.registerAction("restoreDefaultExecutor", KeyStroke.getKeyStroke("released SHIFT"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { myCurrentExecutor = myDefaultExecutor; updatePresentation(); } }); popup.registerAction("invokeAction", KeyStroke.getKeyStroke("shift ENTER"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { popup.handleSelect(true); } }); popup.registerAction("editConfiguration", KeyStroke.getKeyStroke("F4"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { myEditConfiguration = true; popup.handleSelect(true); } }); popup.registerAction("deleteConfiguration", KeyStroke.getKeyStroke("DELETE"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { popup.removeSelected(); } }); popup.registerAction("speedsearch_bksp", KeyStroke.getKeyStroke("BACK_SPACE"), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { SpeedSearch speedSearch = popup.getSpeedSearch(); if (speedSearch.isHoldingFilter()) { speedSearch.backspace(); speedSearch.update(); } } }); for (int i = 0; i < 10; i++) { addNumberAction(popup, i); } } private void addNumberAction(RunListPopup popup, int number) { Action action = createNumberAction(number, popup, myDefaultExecutor); Action action_ = createNumberAction(number, popup, myAlternativeExecutor); popup.registerAction(number + "Action", KeyStroke.getKeyStroke(String.valueOf(number)), action); popup.registerAction(number + "Action_", KeyStroke.getKeyStroke("shift pressed " + number), action_); popup.registerAction(number + "Action1", KeyStroke.getKeyStroke("NUMPAD" + number), action); popup.registerAction(number + "Action_1", KeyStroke.getKeyStroke("shift pressed NUMPAD" + number), action_); } private void updatePresentation() { myPopup.setCaption(getExecutor().getActionName()); } static void execute(final ItemWrapper itemWrapper, final Executor executor) { if (executor == null) { return; } final DataContext dataContext = DataManager.getInstance().getDataContext(); final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null) { itemWrapper.perform(project, executor, dataContext); } } void editConfiguration(@NotNull Project project, @NotNull RunnerAndConfigurationSettings configuration) { final Executor executor = getExecutor(); PropertiesComponent.getInstance().setValue("run.configuration.edit.ad", Boolean.toString(true)); if (RunDialog.editConfiguration(project, configuration, "Edit configuration settings", executor)) { RunManager.getInstance(project).setSelectedConfiguration(configuration); ExecutionUtil.runConfiguration(configuration, executor); } } private static void deleteConfiguration(final Project project, @NotNull final RunnerAndConfigurationSettings configurationSettings) { if (Messages.YES == Messages.showYesNoDialog(project, "Are you sure you want to delete " + configurationSettings.getName() + "?", "Confirmation", Messages.getQuestionIcon())) { RunManager.getInstance(project).removeConfiguration(configurationSettings); } } @Override @NotNull public Executor getExecutor() { return myCurrentExecutor == null ? myDefaultExecutor : myCurrentExecutor; } private static Action createNumberAction(final int number, final ListPopupImpl listPopup, final Executor executor) { return new MyAbstractAction(listPopup, number, executor); } private abstract static class Wrapper { private int myMnemonic = -1; private final boolean myAddSeparatorAbove; private boolean myChecked; protected Wrapper(boolean addSeparatorAbove) { myAddSeparatorAbove = addSeparatorAbove; } public int getMnemonic() { return myMnemonic; } public boolean isChecked() { return myChecked; } public void setChecked(boolean checked) { myChecked = checked; } public void setMnemonic(int mnemonic) { myMnemonic = mnemonic; } public boolean addSeparatorAbove() { return myAddSeparatorAbove; } @Nullable public abstract Icon getIcon(); public abstract String getText(); public boolean canBeDeleted() { return false; } @Override public String toString() { return "Wrapper[" + getText() + "]"; } } public abstract static class ItemWrapper<T> extends Wrapper { private final T myValue; private boolean myDynamic; protected ItemWrapper(@Nullable final T value) { this(value, false); } protected ItemWrapper(@Nullable final T value, boolean addSeparatorAbove) { super(addSeparatorAbove); myValue = value; } public T getValue() { return myValue; } public boolean isDynamic() { return myDynamic; } public void setDynamic(final boolean b) { myDynamic = b; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ItemWrapper)) return false; ItemWrapper that = (ItemWrapper)o; if (myValue != null ? !myValue.equals(that.myValue) : that.myValue != null) return false; return true; } @Override public int hashCode() { return myValue != null ? myValue.hashCode() : 0; } public abstract void perform(@NotNull final Project project, @NotNull final Executor executor, @NotNull final DataContext context); @Nullable public ConfigurationType getType() { return null; } public boolean available(Executor executor) { return false; } public boolean hasActions() { return false; } public PopupStep getNextStep(Project project, ChooseRunConfigurationPopup action) { return PopupStep.FINAL_CHOICE; } public static ItemWrapper wrap(@NotNull final Project project, @NotNull final RunnerAndConfigurationSettings settings, final boolean dynamic) { final ItemWrapper result = wrap(project, settings); result.setDynamic(dynamic); return result; } public static ItemWrapper wrap(@NotNull final Project project, @NotNull final RunnerAndConfigurationSettings settings) { return new ItemWrapper<RunnerAndConfigurationSettings>(settings) { @Override public void perform(@NotNull Project project, @NotNull Executor executor, @NotNull DataContext context) { RunnerAndConfigurationSettings config = getValue(); RunManager.getInstance(project).setSelectedConfiguration(config); MacroManager.getInstance().cacheMacrosPreview(context); ExecutionUtil.runConfiguration(config, executor); } @Override public ConfigurationType getType() { return getValue().getType(); } @Override public Icon getIcon() { return RunManagerEx.getInstanceEx(project).getConfigurationIcon(getValue(), true); } @Override public String getText() { return Executor.shortenNameIfNeed(getValue().getName()) + getValue().getConfiguration().getPresentableType(); } @Override public boolean hasActions() { return true; } @Override public boolean available(Executor executor) { return ProgramRunnerUtil.getRunner(executor.getId(), getValue()) != null; } @Override public PopupStep getNextStep(@NotNull final Project project, @NotNull final ChooseRunConfigurationPopup action) { return new ConfigurationActionsStep(project, action, getValue(), isDynamic()); } }; } @Override public boolean canBeDeleted() { return !isDynamic() && getValue() instanceof RunnerAndConfigurationSettings; } } private static final class ConfigurationListPopupStep extends BaseListPopupStep<ItemWrapper> { private final Project myProject; private final ChooseRunConfigurationPopup myAction; private int myDefaultConfiguration = -1; private ConfigurationListPopupStep(@NotNull final ChooseRunConfigurationPopup action, @NotNull final Project project, @NotNull final ExecutorProvider executorProvider, @NotNull final String title) { super(title, createSettingsList(project, executorProvider, true)); myProject = project; myAction = action; if (-1 == getDefaultOptionIndex()) { myDefaultConfiguration = getDynamicIndex(); } } private int getDynamicIndex() { int i = 0; for (final ItemWrapper wrapper : getValues()) { if (wrapper.isDynamic()) { return i; } i++; } return -1; } @Override public boolean isAutoSelectionEnabled() { return false; } @Override public ListSeparator getSeparatorAbove(ItemWrapper value) { if (value.addSeparatorAbove()) return new ListSeparator(); final List<ItemWrapper> configurations = getValues(); final int index = configurations.indexOf(value); if (index > 0 && index <= configurations.size() - 1) { final ItemWrapper aboveConfiguration = configurations.get(index - 1); if (aboveConfiguration != null && aboveConfiguration.isDynamic() != value.isDynamic()) { return new ListSeparator(); } final ConfigurationType currentType = value.getType(); final ConfigurationType aboveType = aboveConfiguration == null ? null : aboveConfiguration.getType(); if (aboveType != currentType && currentType != null) { return new ListSeparator(); // new ListSeparator(currentType.getDisplayName()); } } return null; } @Override public boolean isSpeedSearchEnabled() { return true; } @Override public int getDefaultOptionIndex() { final RunnerAndConfigurationSettings currentConfiguration = RunManager.getInstance(myProject).getSelectedConfiguration(); if (currentConfiguration == null && myDefaultConfiguration != -1) { return myDefaultConfiguration; } return currentConfiguration instanceof RunnerAndConfigurationSettingsImpl ? getValues() .indexOf(ItemWrapper.wrap(myProject, currentConfiguration)) : -1; } @Override public PopupStep onChosen(final ItemWrapper wrapper, boolean finalChoice) { if (myAction.myEditConfiguration) { final Object o = wrapper.getValue(); if (o instanceof RunnerAndConfigurationSettingsImpl) { return doFinalStep(() -> myAction.editConfiguration(myProject, (RunnerAndConfigurationSettings)o)); } } if (finalChoice && wrapper.available(myAction.getExecutor())) { return doFinalStep(() -> { if (myAction.getExecutor() == myAction.myAlternativeExecutor) { PropertiesComponent.getInstance().setValue(myAction.myAddKey, Boolean.toString(true)); } wrapper.perform(myProject, myAction.getExecutor(), DataManager.getInstance().getDataContext()); }); } else { return wrapper.getNextStep(myProject, myAction); } } @Override public boolean hasSubstep(ItemWrapper selectedValue) { return selectedValue.hasActions(); } @NotNull @Override public String getTextFor(ItemWrapper value) { return value.getText(); } @Override public Icon getIconFor(ItemWrapper value) { return value.getIcon(); } } private static final class ConfigurationActionsStep extends BaseListPopupStep<ActionWrapper> { @NotNull private final RunnerAndConfigurationSettings mySettings; @NotNull private final Project myProject; private ConfigurationActionsStep(@NotNull final Project project, ChooseRunConfigurationPopup action, @NotNull final RunnerAndConfigurationSettings settings, final boolean dynamic) { super(null, buildActions(project, action, settings, dynamic)); myProject = project; mySettings = settings; } @NotNull public RunnerAndConfigurationSettings getSettings() { return mySettings; } public String getName() { return Executor.shortenNameIfNeed(mySettings.getName()); } public Icon getIcon() { return RunManagerEx.getInstanceEx(myProject).getConfigurationIcon(mySettings); } @Override public ListSeparator getSeparatorAbove(ActionWrapper value) { return value.addSeparatorAbove() ? new ListSeparator() : null; } private static ActionWrapper[] buildActions(@NotNull final Project project, final ChooseRunConfigurationPopup action, @NotNull final RunnerAndConfigurationSettings settings, final boolean dynamic) { final List<ActionWrapper> result = new ArrayList<>(); final ExecutionTarget active = ExecutionTargetManager.getActiveTarget(project); for (final ExecutionTarget eachTarget : ExecutionTargetManager.getTargetsToChooseFor(project, settings.getConfiguration())) { result.add(new ActionWrapper(eachTarget.getDisplayName(), eachTarget.getIcon()) { { setChecked(eachTarget.equals(active)); } @Override public void perform() { final RunManager manager = RunManager.getInstance(project); if (dynamic) { manager.setTemporaryConfiguration(settings); } manager.setSelectedConfiguration(settings); ExecutionTargetManager.setActiveTarget(project, eachTarget); ExecutionUtil.runConfiguration(settings, action.getExecutor()); } }); } boolean isFirst = true; for (final Executor executor : ExecutorRegistry.getInstance().getRegisteredExecutors()) { final ProgramRunner runner = ProgramRunner.getRunner(executor.getId(), settings.getConfiguration()); if (runner != null) { result.add(new ActionWrapper(executor.getActionName(), executor.getIcon(), isFirst) { @Override public void perform() { final RunManager manager = RunManager.getInstance(project); if (dynamic) { manager.setTemporaryConfiguration(settings); } manager.setSelectedConfiguration(settings); ExecutionUtil.runConfiguration(settings, executor); } }); isFirst = false; } } result.add(new ActionWrapper("Edit...", AllIcons.Actions.EditSource, true) { @Override public void perform() { if (dynamic) { RunManager.getInstance(project).setTemporaryConfiguration(settings); } action.editConfiguration(project, settings); } }); if (settings.isTemporary() || dynamic) { result.add(new ActionWrapper("Save configuration", AllIcons.Actions.Menu_saveall) { @Override public void perform() { final RunManager manager = RunManager.getInstance(project); if (dynamic) { manager.setTemporaryConfiguration(settings); } manager.makeStable(settings); } }); } result.add(new ActionWrapper("Delete", AllIcons.Actions.Cancel) { @Override public void perform() { deleteConfiguration(project, settings); } }); return result.toArray(new ActionWrapper[0]); } @Override public PopupStep onChosen(final ActionWrapper selectedValue, boolean finalChoice) { return doFinalStep(() -> selectedValue.perform()); } @Override public Icon getIconFor(ActionWrapper aValue) { return aValue.getIcon(); } @NotNull @Override public String getTextFor(ActionWrapper value) { return value.getText(); } } private abstract static class ActionWrapper extends Wrapper { private final String myName; private final Icon myIcon; private ActionWrapper(String name, Icon icon) { this(name, icon, false); } private ActionWrapper(String name, Icon icon, boolean addSeparatorAbove) { super(addSeparatorAbove); myName = name; myIcon = icon; } public abstract void perform(); @Override public String getText() { return myName; } @Override public Icon getIcon() { return myIcon; } } private static class RunListElementRenderer extends PopupListElementRenderer { private JLabel myLabel; private final ListPopupImpl myPopup1; private final boolean myHasSideBar; private RunListElementRenderer(ListPopupImpl popup, boolean hasSideBar) { super(popup); myPopup1 = popup; myHasSideBar = hasSideBar; } @Override protected JComponent createItemComponent() { if (myLabel == null) { myLabel = new JLabel(); myLabel.setPreferredSize(new JLabel("8.").getPreferredSize()); } final JComponent result = super.createItemComponent(); result.add(myLabel, BorderLayout.WEST); return result; } @Override protected void customizeComponent(JList list, Object value, boolean isSelected) { super.customizeComponent(list, value, isSelected); myLabel.setVisible(myHasSideBar); ListPopupStep<Object> step = myPopup1.getListStep(); boolean isSelectable = step.isSelectable(value); myLabel.setEnabled(isSelectable); myLabel.setIcon(null); if (isSelected) { setSelected(myLabel); } else { setDeselected(myLabel); } if (value instanceof Wrapper) { Wrapper wrapper = (Wrapper)value; final int mnemonic = wrapper.getMnemonic(); if (mnemonic != -1 && !myPopup1.getSpeedSearch().isHoldingFilter()) { myLabel.setText(mnemonic + "."); myLabel.setDisplayedMnemonicIndex(0); } else { if (wrapper.isChecked()) { myTextLabel.setIcon(isSelected ? RunConfigurationsComboBoxAction.CHECKED_SELECTED_ICON : RunConfigurationsComboBoxAction.CHECKED_ICON); } else { if (myTextLabel.getIcon() == null) { myTextLabel.setIcon(RunConfigurationsComboBoxAction.EMPTY_ICON); } } myLabel.setText(""); } } } } private static class MyAbstractAction extends AbstractAction implements DumbAware { private final ListPopupImpl myListPopup; private final int myNumber; private final Executor myExecutor; MyAbstractAction(ListPopupImpl listPopup, int number, Executor executor) { myListPopup = listPopup; myNumber = number; myExecutor = executor; } @Override public void actionPerformed(ActionEvent e) { if (myListPopup.getSpeedSearch().isHoldingFilter()) return; for (final Object item : myListPopup.getListStep().getValues()) { if (item instanceof ItemWrapper && ((ItemWrapper)item).getMnemonic() == myNumber) { myListPopup.setFinalRunnable(() -> execute((ItemWrapper)item, myExecutor)); myListPopup.closeOk(null); } } } } private class RunListPopup extends ListPopupImpl { RunListPopup(ListPopupStep step) { super(step); registerActions(this); } protected RunListPopup(WizardPopup aParent, ListPopupStep aStep, Object parentValue) { super(aParent, aStep, parentValue); registerActions(this); } @Override protected WizardPopup createPopup(WizardPopup parent, PopupStep step, Object parentValue) { return new RunListPopup(parent, (ListPopupStep)step, parentValue); } @Override public void handleSelect(boolean handleFinalChoices, InputEvent e) { if (e instanceof MouseEvent && e.isShiftDown()) { handleShiftClick(handleFinalChoices, e, this); return; } _handleSelect(handleFinalChoices, e); } private void _handleSelect(boolean handleFinalChoices, InputEvent e) { super.handleSelect(handleFinalChoices, e); } protected void handleShiftClick(boolean handleFinalChoices, final InputEvent inputEvent, final RunListPopup popup) { myCurrentExecutor = myAlternativeExecutor; popup._handleSelect(handleFinalChoices, inputEvent); } @Override protected ListCellRenderer getListElementRenderer() { boolean hasSideBar = false; for (Object each : getListStep().getValues()) { if (each instanceof Wrapper) { if (((Wrapper)each).getMnemonic() != -1) { hasSideBar = true; break; } } } return new RunListElementRenderer(this, hasSideBar); } public void removeSelected() { final PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); if (!propertiesComponent.isTrueValue("run.configuration.delete.ad")) { propertiesComponent.setValue("run.configuration.delete.ad", Boolean.toString(true)); } final int index = getSelectedIndex(); if (index == -1) { return; } final Object o = getListModel().get(index); if (o instanceof ItemWrapper && ((ItemWrapper)o).canBeDeleted()) { deleteConfiguration(myProject, (RunnerAndConfigurationSettings)((ItemWrapper)o).getValue()); getListModel().deleteItem(o); final List<Object> values = getListStep().getValues(); values.remove(o); if (index < values.size()) { onChildSelectedFor(values.get(index)); } else if (index - 1 >= 0) { onChildSelectedFor(values.get(index - 1)); } } } @Override protected boolean isResizable() { return true; } } private static class FolderWrapper extends ItemWrapper<String> { private final Project myProject; private final ExecutorProvider myExecutorProvider; private final List<RunnerAndConfigurationSettings> myConfigurations; private FolderWrapper(Project project, ExecutorProvider executorProvider, @Nullable String value, List<RunnerAndConfigurationSettings> configurations) { super(value); myProject = project; myExecutorProvider = executorProvider; myConfigurations = configurations; } @Override public void perform(@NotNull Project project, @NotNull Executor executor, @NotNull DataContext context) { RunManager runManager = RunManager.getInstance(project); RunnerAndConfigurationSettings selectedConfiguration = runManager.getSelectedConfiguration(); if (myConfigurations.contains(selectedConfiguration)) { runManager.setSelectedConfiguration(selectedConfiguration); ExecutionUtil.runConfiguration(selectedConfiguration, myExecutorProvider.getExecutor()); } } @Nullable @Override public Icon getIcon() { return AllIcons.Nodes.Folder; } @Override public String getText() { return getValue(); } @Nullable @Override public ConfigurationType getType() { return Registry.is("run.popup.move.folders.to.top") || myConfigurations.isEmpty() ? null : myConfigurations.get(0).getType(); } @Override public boolean hasActions() { return true; } @Override public PopupStep getNextStep(Project project, ChooseRunConfigurationPopup action) { List<ConfigurationActionsStep> steps = new ArrayList<>(); for (RunnerAndConfigurationSettings settings : myConfigurations) { steps.add(new ConfigurationActionsStep(project, action, settings, false)); } return new FolderStep(myProject, myExecutorProvider, null, steps, action); } } private static final class FolderStep extends BaseListPopupStep<ConfigurationActionsStep> { private final Project myProject; private final ChooseRunConfigurationPopup myPopup; private final ExecutorProvider myExecutorProvider; private FolderStep(Project project, ExecutorProvider executorProvider, String folderName, List<ConfigurationActionsStep> children, ChooseRunConfigurationPopup popup) { super(folderName, children, new ArrayList<>()); myProject = project; myExecutorProvider = executorProvider; myPopup = popup; } @Override public PopupStep onChosen(final ConfigurationActionsStep selectedValue, boolean finalChoice) { if (finalChoice) { if (myPopup.myEditConfiguration) { final RunnerAndConfigurationSettings settings = selectedValue.getSettings(); return doFinalStep(() -> myPopup.editConfiguration(myProject, settings)); } return doFinalStep(() -> { RunnerAndConfigurationSettings settings = selectedValue.getSettings(); RunManager.getInstance(myProject).setSelectedConfiguration(settings); ExecutionUtil.runConfiguration(settings, myExecutorProvider.getExecutor()); }); } else { return selectedValue; } } @Override public Icon getIconFor(ConfigurationActionsStep aValue) { return aValue.getIcon(); } @NotNull @Override public String getTextFor(ConfigurationActionsStep value) { return value.getName(); } @Override public boolean hasSubstep(ConfigurationActionsStep selectedValue) { return !selectedValue.getValues().isEmpty(); } } @NotNull public static List<ItemWrapper> createSettingsList(@NotNull Project project, @NotNull ExecutorProvider executorProvider, boolean isCreateEditAction) { List<ItemWrapper> result = new ArrayList<>(); if (isCreateEditAction) { result.add(createEditAction()); } final RunnerAndConfigurationSettings selectedConfiguration = RunManager.getInstance(project).getSelectedConfiguration(); if (selectedConfiguration != null) { boolean isFirst = true; final ExecutionTarget activeTarget = ExecutionTargetManager.getActiveTarget(project); for (ExecutionTarget eachTarget : ExecutionTargetManager.getTargetsToChooseFor(project, selectedConfiguration.getConfiguration())) { result.add(new ItemWrapper<ExecutionTarget>(eachTarget, isFirst) { { setChecked(getValue().equals(activeTarget)); } @Override public Icon getIcon() { return getValue().getIcon(); } @Override public String getText() { return getValue().getDisplayName(); } @Override public void perform(@NotNull final Project project, @NotNull final Executor executor, @NotNull DataContext context) { ExecutionTargetManager.setActiveTarget(project, getValue()); ExecutionUtil.runConfiguration(selectedConfiguration, executor); } @Override public boolean available(Executor executor) { return true; } }); isFirst = false; } } Map<RunnerAndConfigurationSettings, ItemWrapper> wrappedExisting = new LinkedHashMap<>(); List<FolderWrapper> folderWrappers = new SmartList<>(); for (Map<String, List<RunnerAndConfigurationSettings>> structure : RunManagerImpl.getInstanceImpl(project).getConfigurationsGroupedByTypeAndFolder(false).values()) { for (Map.Entry<String, List<RunnerAndConfigurationSettings>> entry : structure.entrySet()) { final String folderName = entry.getKey(); if (folderName != null) { boolean isSelected = entry.getValue().contains(selectedConfiguration); if (isSelected) { assert selectedConfiguration != null; } FolderWrapper folderWrapper = new FolderWrapper(project, executorProvider, folderName + (isSelected ? " (mnemonic is to \"" + selectedConfiguration.getName() + "\")" : ""), entry.getValue()); if (isSelected) { folderWrapper.setMnemonic(1); } folderWrappers.add(folderWrapper); } else { for (RunnerAndConfigurationSettings configuration : entry.getValue()) { final ItemWrapper wrapped = ItemWrapper.wrap(project, configuration); if (configuration == selectedConfiguration) { wrapped.setMnemonic(1); } wrappedExisting.put(configuration, wrapped); } } } } boolean moveFoldersToTop = Registry.is("run.popup.move.folders.to.top"); if (moveFoldersToTop) { result.addAll(folderWrappers); } if (!DumbService.isDumb(project)) { populateWithDynamicRunners(result, wrappedExisting, project, RunManagerEx.getInstanceEx(project), selectedConfiguration); } final int topIndex = result.size() - 1; result.addAll(wrappedExisting.values()); if (!moveFoldersToTop) { for (FolderWrapper folderWrapper : folderWrappers) { int bestIndex = topIndex; for (int index = topIndex; index < result.size(); index++) { bestIndex = index; ConfigurationType folderType = ObjectUtils.notNull(folderWrapper.getType(), UnknownConfigurationType.getInstance()); ItemWrapper item = result.get(index); ConfigurationType currentType = item.getType(); int m = currentType == null ? 1 : RunConfigurationListManagerHelperKt.compareTypesForUi(folderType, currentType); if (m < 0 || (m == 0 && !(item instanceof FolderWrapper))) { break; } } result.add(bestIndex, folderWrapper); } } return result; } @NotNull private static ItemWrapper<Void> createEditAction() { ItemWrapper<Void> result = new ItemWrapper<Void>(null) { @Override public Icon getIcon() { return AllIcons.Actions.EditSource; } @Override public String getText() { return UIUtil.removeMnemonic(ActionsBundle.message("action.editRunConfigurations.text")); } @Override public void perform(@NotNull final Project project, @NotNull final Executor executor, @NotNull DataContext context) { if (new EditConfigurationsDialog(project) { @Override protected void init() { setOKButtonText(executor.getStartActionText()); setOKButtonIcon(executor.getIcon()); myExecutor = executor; super.init(); } }.showAndGet()) { ApplicationManager.getApplication().invokeLater(() -> { RunnerAndConfigurationSettings configuration = RunManager.getInstance(project).getSelectedConfiguration(); if (configuration != null) { ExecutionUtil.runConfiguration(configuration, executor); } }, project.getDisposed()); } } @Override public boolean available(Executor executor) { return true; } }; result.setMnemonic(0); return result; } private static void populateWithDynamicRunners(final List<? super ItemWrapper> result, Map<RunnerAndConfigurationSettings, ItemWrapper> existing, final Project project, final RunManager manager, final RunnerAndConfigurationSettings selectedConfiguration) { if (!EventQueue.isDispatchThread()) { return; } final DataContext dataContext = DataManager.getInstance().getDataContext(); final ConfigurationContext context = ConfigurationContext.getFromContext(dataContext); final List<ConfigurationFromContext> producers = PreferredProducerFind.getConfigurationsFromContext(context.getLocation(), context, false); if (producers == null) return; Collections.sort(producers, ConfigurationFromContext.NAME_COMPARATOR); final RunnerAndConfigurationSettings[] preferred = {null}; int i = 2; // selectedConfiguration == null ? 1 : 2; for (final ConfigurationFromContext fromContext : producers) { final RunnerAndConfigurationSettings configuration = fromContext.getConfigurationSettings(); if (existing.keySet().contains(configuration)) { final ItemWrapper wrapper = existing.get(configuration); if (wrapper.getMnemonic() != 1) { wrapper.setMnemonic(i); i++; } } else { if (selectedConfiguration != null && configuration.equals(selectedConfiguration)) continue; if (preferred[0] == null) { preferred[0] = configuration; } //noinspection unchecked final ItemWrapper wrapper = new ItemWrapper(configuration) { @Override public Icon getIcon() { return RunManagerEx.getInstanceEx(project).getConfigurationIcon(configuration); } @Override public String getText() { return Executor.shortenNameIfNeed(configuration.getName()) + configuration.getConfiguration().getPresentableType(); } @Override public boolean available(Executor executor) { return canRun(executor, configuration); } @Override public void perform(@NotNull Project project, @NotNull Executor executor, @NotNull DataContext context) { manager.setTemporaryConfiguration(configuration); RunManager.getInstance(project).setSelectedConfiguration(configuration); ExecutionUtil.runConfiguration(configuration, executor); } @Override public PopupStep getNextStep(@NotNull final Project project, @NotNull final ChooseRunConfigurationPopup action) { return new ConfigurationActionsStep(project, action, configuration, isDynamic()); } @Override public boolean hasActions() { return true; } }; wrapper.setDynamic(true); wrapper.setMnemonic(i); result.add(wrapper); i++; } } } }
extract addActionsForSelected
platform/lang-impl/src/com/intellij/execution/actions/ChooseRunConfigurationPopup.java
extract addActionsForSelected
Java
apache-2.0
a861e820566f089194519d21d5231e106580a8ce
0
akk-team33/lib-patterns,akk-team33/lib-patterns,akk-team33/lib-patterns
package de.team33.test.patterns.expiry.e1; import de.team33.patterns.expiry.e1.Recent; import de.team33.patterns.testing.e1.Parallel; import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.List; import java.util.function.Supplier; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class RecentTest { private static final long LIFETIME = 100; // milliseconds! private static final long MAX_LIFESPAN = LIFETIME + 30; private final Recent<Obsolescing> subject = new Recent<>(Obsolescing::new, LIFETIME); @Test final void obsolencing() throws Exception { final Obsolescing sample = new Obsolescing(); Thread.sleep(MAX_LIFESPAN); assertThrows(IllegalStateException.class, sample::getCreated); } @Test final void simple() throws Exception { // given ... final long time0 = System.currentTimeMillis(); final Obsolescing first = subject.get(); // when ... long counter = 0; while (first == subject.get()) { counter += 1; } final long delta = System.currentTimeMillis() - time0; // then ... assertTrue(delta > LIFETIME, () -> "delta = " + delta); final long finalCounter = counter; assertTrue(finalCounter > 0, () -> "counter = " + finalCounter); assertTrue(finalCounter > 100000, () -> "counter = " + finalCounter); // may fail on a slow system } @Test final void parallel() throws Exception { // given ... final long time0 = System.currentTimeMillis(); final Obsolescing first = subject.get(); // when ... final List<Long> results = Parallel.apply(10, index -> { long counter = 0; while (first == subject.get()) { counter += 1; Thread.sleep(0); // ... to give another thread a chance } return counter; }).reThrowAny().getResults(); final long delta = System.currentTimeMillis() - time0; // then ... assertTrue(delta > LIFETIME, () -> "delta = " + delta); results.forEach(counter -> { assertTrue(counter > 0, () -> "counter = " + counter); // may fail on a very slow system assertTrue(counter > 500, () -> "counter = " + counter); // may fail on a slow system }); } static class Obsolescing { private final Instant created; Obsolescing() { created = Instant.now(); } final Instant getCreated() { return ifAlive(() -> created); } private <R> R ifAlive(final Supplier<R> supplier) { final Instant now = Instant.now(); if (created.plusMillis(MAX_LIFESPAN).isAfter(now)) { return supplier.get(); } throw new IllegalStateException("Instance is outdated - created = " + created + ", now = " + now); } } }
refreshing-01/src/test/java/de/team33/test/patterns/expiry/e1/RecentTest.java
package de.team33.test.patterns.expiry.e1; import de.team33.patterns.expiry.e1.Recent; import de.team33.patterns.testing.e1.Parallel; import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.List; import java.util.function.Supplier; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class RecentTest { private static final long LIFETIME = 100; // milliseconds! private static final long MAX_LIFESPAN = LIFETIME + 30; private final Recent<Obsolescing> subject = new Recent<>(Obsolescing::new, LIFETIME); @Test final void obsolencing() throws Exception { final Obsolescing sample = new Obsolescing(); Thread.sleep(MAX_LIFESPAN); assertThrows(IllegalStateException.class, () -> sample.getCreated()); } @Test final void simple() throws Exception { // given ... final long time0 = System.currentTimeMillis(); final Obsolescing first = subject.get(); // when ... long counter = 0; while (first == subject.get()) { counter += 1; } final long delta = System.currentTimeMillis() - time0; // then ... assertTrue(delta > LIFETIME, () -> "delta = " + delta); final long finalCounter = counter; assertTrue(finalCounter > 0, () -> "counter = " + finalCounter); assertTrue(finalCounter > 100000, () -> "counter = " + finalCounter); // may fail on a slow system } @Test final void parallel() throws Exception { final long time0 = System.currentTimeMillis(); final Obsolescing first = subject.get(); final List<Long> results = Parallel.apply(10, index -> { long counter = 0; while (first == subject.get()) { counter += 1; Thread.sleep(0); // ... to give another thread a chance } return counter; }).reThrowAny().getResults(); final long delta = System.currentTimeMillis() - time0; assertTrue(delta > LIFETIME, () -> "delta = " + delta); results.forEach(counter -> { assertTrue(counter > 0, () -> "counter = " + counter); assertTrue(counter > 500, () -> "counter = " + counter); // may fail on a slow system }); } static class Obsolescing { private final Instant created; Obsolescing() { created = Instant.now(); } final Instant getCreated() { return ifAlive(() -> created); } private <R> R ifAlive(final Supplier<R> supplier) { final Instant now = Instant.now(); if (created.plusMillis(MAX_LIFESPAN).isAfter(now)) { return supplier.get(); } throw new IllegalStateException("Instance is outdated - created = " + created + ", now = " + now); } } }
maintenance-01: small enhancements
refreshing-01/src/test/java/de/team33/test/patterns/expiry/e1/RecentTest.java
maintenance-01: small enhancements
Java
apache-2.0
fb482c34144362ce6d86871ba7b025f21119a85f
0
jesse-gallagher/frostillic.us-Blog,jesse-gallagher/frostillic.us-Blog,jesse-gallagher/frostillic.us-Blog,jesse-gallagher/frostillic.us-Blog
/** * Copyright © 2016-2019 Jesse Gallagher * * 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 controller; import com.darwino.commons.json.JsonException; import com.darwino.commons.util.StringUtil; import javax.mvc.Controller; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import static model.util.PostUtil.PAGE_LENGTH; @Path("/") @Controller public class HomeController extends AbstractPostListController { @GET public String get(@QueryParam("start") String startParam) throws JsonException { String maybeList = maybeList(startParam); if(StringUtil.isEmpty(maybeList)) { models.put("posts", posts.homeList()); //$NON-NLS-1$ models.put("start", 0); //$NON-NLS-1$ } models.put("pageSize", PAGE_LENGTH); //$NON-NLS-1$ return "home.jsp"; //$NON-NLS-1$ } }
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/HomeController.java
/** * Copyright © 2016-2019 Jesse Gallagher * * 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 controller; import com.darwino.commons.json.JsonException; import com.darwino.commons.util.StringUtil; import com.darwino.platform.DarwinoContext; import javax.mvc.Controller; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import static model.util.PostUtil.PAGE_LENGTH; @Path("/") @Controller public class HomeController extends AbstractPostListController { @GET public String get(@QueryParam("start") String startParam) throws JsonException { String maybeList = maybeList(startParam); if(StringUtil.isEmpty(maybeList)) { models.put("posts", posts.homeList()); //$NON-NLS-1$ models.put("start", 0); } models.put("pageSize", PAGE_LENGTH); return "home.jsp"; //$NON-NLS-1$ } }
NLS fix
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/HomeController.java
NLS fix
Java
apache-2.0
197d2616867a8973e97ed8b7820a9a1930636115
0
google/mug,google/mug
package com.google.mu.util; import static com.google.common.collect.Range.atLeast; import static com.google.common.collect.Range.atMost; import static com.google.common.collect.Range.closed; import static com.google.common.collect.Range.closedOpen; import static com.google.common.collect.Range.greaterThan; import static com.google.common.collect.Range.lessThan; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.BinarySearch.inSortedArray; import static com.google.mu.util.BinarySearch.inSortedArrayWithTolerance; import static com.google.mu.util.BinarySearch.inSortedList; import static com.google.mu.util.BinarySearch.inSortedListWithTolerance; import static java.util.Arrays.asList; import static org.junit.Assert.assertThrows; import java.util.Comparator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Range; import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester; import com.google.common.truth.Expect; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; @RunWith(TestParameterInjector.class) public class BinarySearchTest { @Rule public final Expect expect = Expect.create(); @Test public void inRangeInclusive_invalidIndex() { assertThrows(IllegalArgumentException.class, () -> BinarySearch.forInts(closed(2, 0))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forInts(closed(Integer.MAX_VALUE, Integer.MAX_VALUE - 2))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forInts(closed(Integer.MIN_VALUE + 2, Integer.MIN_VALUE))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forInts(closed(Integer.MAX_VALUE, Integer.MIN_VALUE))); } @Test public void forLongs_Inclusive_invalidIndex() { assertThrows(IllegalArgumentException.class, () -> BinarySearch.forLongs(closed(2L, 0L))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forLongs(closed(Long.MAX_VALUE, Long.MAX_VALUE - 2))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forLongs(closed(Long.MIN_VALUE + 2, Long.MIN_VALUE))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forLongs(closed(Long.MAX_VALUE, Long.MIN_VALUE))); } @Test public void forInts_empty() { assertThat(BinarySearch.forInts(closedOpen(0, 0)).find((l, i, h) -> 0)).isEmpty(); assertThat(BinarySearch.forInts(closedOpen(0, 0)).rangeOf((l, i, h) -> 0)) .isEqualTo(Range.closedOpen(0, 0)); assertThat(BinarySearch.forInts(closedOpen(0, 0)).insertionPointFor((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(closedOpen(0, 0)).insertionPointBefore((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(closedOpen(0, 0)).insertionPointAfter((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(greaterThan(Integer.MAX_VALUE)).rangeOf((l, i, h) -> 0)) .isEqualTo(Range.closedOpen(Integer.MAX_VALUE, Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(greaterThan(Integer.MAX_VALUE)).find((l, i, h) -> 0)) .isEmpty(); assertThat(BinarySearch.forInts(lessThan(Integer.MIN_VALUE)).find((l, i, h) -> 0)) .isEmpty(); } @Test public void forLongs_empty() { assertThat(BinarySearch.forLongs(closedOpen(0L, 0L)).find((l, i, h) -> 0)).isEmpty(); assertThat(BinarySearch.forLongs(closedOpen(0L, 0L)).rangeOf((l, i, h) -> 0)) .isEqualTo(Range.closedOpen(0L, 0L)); assertThat(BinarySearch.forLongs(closedOpen(0L, 0L)).insertionPointFor((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0L)); assertThat(BinarySearch.forLongs(closedOpen(0L, 0L)).insertionPointBefore((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0L)); assertThat(BinarySearch.forLongs(closedOpen(0L, 0L)).insertionPointAfter((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0L)); assertThat(BinarySearch.forLongs(greaterThan(Long.MAX_VALUE)).rangeOf((l, i, h) -> 0)) .isEqualTo(Range.closedOpen(Long.MAX_VALUE, Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(greaterThan(Long.MAX_VALUE)).find((l, i, h) -> 0)) .isEmpty(); assertThat(BinarySearch.forLongs(lessThan(Long.MIN_VALUE)).find((l, i, h) -> 0)) .isEmpty(); } @Test public void forInts_singleCandidateRange_found() { assertThat(BinarySearch.forInts(closed(1, 1)).find((l, i, h) -> Integer.compare(i, 1))) .hasValue(1); assertThat(BinarySearch.forInts(closed(1, 1)).rangeOf((l, i, h) -> Integer.compare(i, 1))) .isEqualTo(Range.closed(1, 1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointFor((l, i, h) -> Integer.compare(i, 1))) .isEqualTo(InsertionPoint.at(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointBefore((l, i, h) -> Integer.compare(i, 1))) .isEqualTo(InsertionPoint.before(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointAfter((l, i, h) -> Integer.compare(i, 1))) .isEqualTo(InsertionPoint.after(1)); } @Test public void forLongs_singleCandidateRange_found() { assertThat(BinarySearch.forLongs(closed(1L, 1L)).find((l, i, h) -> Long.compare(i, 1))) .hasValue(1L); assertThat(BinarySearch.forLongs(closed(1L, 1L)).rangeOf((l, i, h) -> Long.compare(i, 1))) .isEqualTo(Range.closed(1L, 1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointFor((l, i, h) -> Long.compare(i, 1))) .isEqualTo(InsertionPoint.at(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointBefore((l, i, h) -> Long.compare(i, 1))) .isEqualTo(InsertionPoint.before(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointAfter((l, i, h) -> Long.compare(i, 1))) .isEqualTo(InsertionPoint.after(1L)); } @Test public void forInts_singleCandidateRange_shouldBeBefore() { assertThat(BinarySearch.forInts(closed(1, 1)).find((l, i, h) -> Integer.compare(0, i))) .isEmpty(); assertThat(BinarySearch.forInts(closed(1, 1)).rangeOf((l, i, h) -> Integer.compare(0, i))) .isEqualTo(Range.closedOpen(1, 1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointFor((l, i, h) -> Integer.compare(0, i))) .isEqualTo(InsertionPoint.before(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointBefore((l, i, h) -> Integer.compare(0, i))) .isEqualTo(InsertionPoint.before(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointAfter((l, i, h) -> Integer.compare(0, i))) .isEqualTo(InsertionPoint.before(1)); } @Test public void forInts_singleCandidateRange_shouldBeAfter() { assertThat(BinarySearch.forInts(closed(1, 1)).find((l, i, h) -> Integer.compare(10, i))) .isEmpty(); assertThat(BinarySearch.forInts(closed(1, 1)).rangeOf((l, i, h) -> Integer.compare(10, i))) .isEqualTo(Range.closedOpen(2, 2)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointFor((l, i, h) -> Integer.compare(10, i))) .isEqualTo(InsertionPoint.after(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointBefore((l, i, h) -> Integer.compare(10, i))) .isEqualTo(InsertionPoint.after(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointAfter((l, i, h) -> Integer.compare(10, i))) .isEqualTo(InsertionPoint.after(1)); } @Test public void forLongs_singleCandidateRange_shouldBeBefore() { assertThat(BinarySearch.forLongs(closed(1L, 1L)).find((l, i, h) -> Long.compare(0, i))) .isEmpty(); assertThat(BinarySearch.forLongs(closed(1L, 1L)).rangeOf((l, i, h) -> Long.compare(0, i))) .isEqualTo(Range.closedOpen(1L, 1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointFor((l, i, h) -> Long.compare(0, i))) .isEqualTo(InsertionPoint.before(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointBefore((l, i, h) -> Long.compare(0, i))) .isEqualTo(InsertionPoint.before(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointAfter((l, i, h) -> Long.compare(0, i))) .isEqualTo(InsertionPoint.before(1L)); } @Test public void forLongs_singleCandidateRange_shouldBeAfter() { assertThat(BinarySearch.forLongs(closed(1L, 1L)).find((l, i, h) -> Long.compare(3, i))) .isEmpty(); assertThat(BinarySearch.forLongs(closed(1L, 1L)).rangeOf((l, i, h) -> Long.compare(3, i))) .isEqualTo(Range.closedOpen(2L, 2L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointFor((l, i, h) -> Long.compare(3, i))) .isEqualTo(InsertionPoint.after(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointBefore((l, i, h) -> Long.compare(3, i))) .isEqualTo(InsertionPoint.after(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointAfter((l, i, h) -> Long.compare(3, i))) .isEqualTo(InsertionPoint.after(1L)); } @Test public void forInts_useMinValueForLeft() { assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).find((l, i, h) -> Integer.MIN_VALUE)) .isEmpty(); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).rangeOf((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(Range.closedOpen(Integer.MIN_VALUE, Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointFor((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointBefore((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointAfter((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); } @Test public void forInts_preventsUderflow_shouldBeBefore() { assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Integer.MIN_VALUE, Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); } @Test public void forInts_useMaxValueForRight() { assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).find((l, i, h) -> Integer.MAX_VALUE)) .isEmpty(); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).rangeOf((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(Range.closedOpen(Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 1)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointFor((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointBefore((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointAfter((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); } @Test public void forInts_preventsUnderflow_shouldBeAfter() { assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.closedOpen(Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 1)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); } @Test public void forLongs_useMinValueForLeft() { assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).find((l, i, h) -> Integer.MIN_VALUE)) .isEmpty(); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).rangeOf((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE, Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointFor((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointBefore((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointAfter((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); } @Test public void forLongs_preventsUderflow_shouldBeBefore() { assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE, Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); } @Test public void forLongs_useMaxValueForRight() { assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).find((l, i, h) -> Integer.MAX_VALUE)) .isEmpty(); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).rangeOf((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE + 1, Long.MIN_VALUE + 1)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointFor((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointBefore((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointAfter((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); } @Test public void forLongs_preventsUnderflow_shouldBeAfter() { assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE + 1, Long.MIN_VALUE + 1)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); } @Test public void forInts_preventsOverflow_shouldBeBefore() { assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Integer.MAX_VALUE, Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MAX_VALUE)); } @Test public void forInts_preventsOverflow_shouldBeAfter() { assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Integer.MAX_VALUE, Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); } @Test public void forLongs_preventsOverflow_shouldBeBefore() { assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Long.MAX_VALUE, Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MAX_VALUE)); } @Test public void forLongs_preventsOverflow_shouldBeAfter() { assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Long.MAX_VALUE, Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); } @Test public void forInts_maxRange_shouldBeBefore() { assertThat(BinarySearch.forInts().find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forInts().rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Integer.MIN_VALUE, Integer.MIN_VALUE)); assertThat(BinarySearch.forInts().insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts().insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts().insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); } @Test public void forInts_maxRange_shouldBeAfter() { assertThat(BinarySearch.forInts().find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forInts().rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Integer.MAX_VALUE, Integer.MAX_VALUE)); assertThat(BinarySearch.forInts().insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts().insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts().insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); } @Test public void forLongs_maxRange_shouldBeBefore() { assertThat(BinarySearch.forLongs().find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forLongs().rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE, Long.MIN_VALUE)); assertThat(BinarySearch.forLongs().insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs().insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs().insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); } @Test public void forLongs_maxRange_shouldBeAfter() { assertThat(BinarySearch.forLongs().find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forLongs().rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Long.MAX_VALUE, Long.MAX_VALUE)); assertThat(BinarySearch.forLongs().insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs().insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs().insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); } @Test public void forInts_maxPositiveRange_shouldBeBefore() { assertThat(BinarySearch.forInts(atLeast(0)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forInts(atLeast(0)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(0, 0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(0)); } @Test public void forInts_maxPositiveRange_shouldBeAfter() { assertThat(BinarySearch.forInts(atLeast(0)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forInts(atLeast(0)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Integer.MAX_VALUE, Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); } @Test public void forLongs_maxPositiveRange_shouldBeAfter() { assertThat(BinarySearch.forLongs(atLeast(0L)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forLongs(atLeast(0L)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Long.MAX_VALUE, Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); } @Test public void forInts_maxNegativeRange_shouldBeAfter() { assertThat(BinarySearch.forInts(Range.lessThan(0)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forInts(Range.lessThan(0)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.closedOpen(0, 0)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1)); } @Test public void forLongs_maxNegativeRange_shouldBeBefore() { assertThat(BinarySearch.forLongs(Range.lessThan(0L)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE, Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); } @Test public void forLongs_maxNegativeRange_shouldBeAfter() { assertThat(BinarySearch.forLongs(Range.lessThan(0L)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.closedOpen(0L, 0L)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1L)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1L)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1L)); } @Test public void forInts_maxRange_found( @TestParameter(valuesProvider = IntValues.class) int target) { assertThat( BinarySearch.forInts(Range.<Integer>all()) .find((l, i, h) -> Integer.compare(target, i))) .hasValue(target); assertThat( BinarySearch.forInts(Range.<Integer>all()) .rangeOf((l, i, h) -> Integer.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat( BinarySearch.forInts(Range.<Integer>all()) .insertionPointFor((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat( BinarySearch.forInts(Range.<Integer>all()) .insertionPointBefore((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat( BinarySearch.forInts(Range.<Integer>all()) .insertionPointAfter((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forInts_maxNegativeRange_found( @TestParameter(valuesProvider = NegativeValues.class) int target) { assertThat(BinarySearch.forInts(Range.lessThan(0)).find((l, i, h) -> Integer.compare(target, i))) .hasValue(target); assertThat(BinarySearch.forInts(Range.lessThan(0)).rangeOf((l, i, h) -> Integer.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointFor((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointBefore((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointAfter((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forLongs_maxRange_found( @TestParameter(valuesProvider = LongValues.class) long target) { assertThat( BinarySearch.forLongs(Range.<Long>all()) .find((l, i, h) -> Long.compare(target, i))) .hasValue(target); assertThat( BinarySearch.forLongs(Range.<Long>all()) .rangeOf((l, i, h) -> Long.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat( BinarySearch.forLongs(Range.<Long>all()) .insertionPointFor((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat( BinarySearch.forLongs(Range.<Long>all()) .insertionPointBefore((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat( BinarySearch.forLongs(Range.<Long>all()) .insertionPointAfter((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forLongs_maxNegativeRange_found( @TestParameter(valuesProvider = NegativeLongValues.class) long target) { assertThat(BinarySearch.forLongs(Range.lessThan(0L)).find((l, i, h) -> Long.compare(target, i))) .hasValue(target); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).rangeOf((l, i, h) -> Long.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointFor((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointBefore((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointAfter((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forInts_maxNonNegativeRange_found( @TestParameter(valuesProvider = NonNegativeValues.class) int target) { assertThat(BinarySearch.forInts(atLeast(0)).find((l, i, h) -> Integer.compare(target, i))) .hasValue(target); assertThat(BinarySearch.forInts(atLeast(0)).rangeOf((l, i, h) -> Integer.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointFor((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointBefore((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointAfter((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forLongs_maxNonNegativeRange_found( @TestParameter(valuesProvider = NonNegativeLongValues.class) long target) { assertThat(BinarySearch.forLongs(atLeast(0L)).find((l, i, h) -> Long.compare(target, i))) .hasValue(target); assertThat(BinarySearch.forLongs(atLeast(0L)).rangeOf((l, i, h) -> Long.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointFor((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointBefore((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointAfter((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forInts_maxNonNegativeRange_negativeNotFound( @TestParameter(valuesProvider = NegativeValues.class) int target) { assertThat(BinarySearch.forInts(atLeast(0)).find((l, i, h) -> Integer.compare(target, i))) .isEmpty(); assertThat(BinarySearch.forInts(atLeast(0)).rangeOf((l, i, h) -> Integer.compare(target, i))) .isEqualTo(Range.closedOpen(0, 0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointFor((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointBefore((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointAfter((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(0)); } @Test public void forLongs_maxNonNegativeRange_negativeNotFound( @TestParameter(valuesProvider = NegativeValues.class) int target) { assertThat(BinarySearch.forLongs(atLeast(0L)).find((l, i, h) -> Long.compare(target, i))) .isEmpty(); assertThat(BinarySearch.forLongs(atLeast(0L)).rangeOf((l, i, h) -> Long.compare(target, i))) .isEqualTo(Range.closedOpen(0L, 0L)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointFor((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(0L)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointBefore((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(0L)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointAfter((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(0L)); } @Test public void binarySearch_inSortedIntArray_found() { int[] sorted = new int[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(20)).hasValue(1); assertThat(inSortedArray(sorted).rangeOf(20)).isEqualTo(Range.closed(1, 1)); assertThat(inSortedArray(sorted).insertionPointFor(20)).isEqualTo(InsertionPoint.at(1)); assertThat(inSortedArray(sorted).insertionPointBefore(20)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(20)).isEqualTo(InsertionPoint.after(1)); } @Test public void binarySearch_inSortedIntArray_notFoundInTheMiddle() { int[] sorted = new int[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(19)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(19)).isEqualTo(Range.closedOpen(1, 1)); assertThat(inSortedArray(sorted).insertionPointFor(19)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointBefore(19)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(19)).isEqualTo(InsertionPoint.before(1)); } @Test public void binarySearch_inSortedIntArray_notFoundAtTheBeginning() { int[] sorted = new int[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(-1)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(-1)).isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedArray(sorted).insertionPointFor(Integer.MIN_VALUE)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArray(sorted).insertionPointBefore(-1)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArray(sorted).insertionPointAfter(0)).isEqualTo(InsertionPoint.before(0)); } @Test public void binarySearch_inSortedIntArray_notFoundAtTheEnd() { int[] sorted = new int[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(41)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(Integer.MAX_VALUE)).isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedArray(sorted).insertionPointFor(50)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArray(sorted).insertionPointBefore(Integer.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArray(sorted).insertionPointAfter(Integer.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedLongArray_found() { long[] sorted = new long[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(20L)).hasValue(1); assertThat(inSortedArray(sorted).rangeOf(20L)).isEqualTo(Range.closed(1, 1)); assertThat(inSortedArray(sorted).insertionPointFor(20L)).isEqualTo(InsertionPoint.at(1)); assertThat(inSortedArray(sorted).insertionPointBefore(20L)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(20L)).isEqualTo(InsertionPoint.after(1)); } @Test public void binarySearch_inSortedLongArray_notFoundInTheMiddle() { long[] sorted = new long[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(19L)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(19L)).isEqualTo(Range.closedOpen(1, 1)); assertThat(inSortedArray(sorted).insertionPointFor(19L)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointBefore(19L)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(19L)).isEqualTo(InsertionPoint.before(1)); } @Test public void binarySearch_inSortedLongArray_notFoundAtTheBeginning() { long[] sorted = new long[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(-1L)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(-1L)).isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedArray(sorted).insertionPointFor(Long.MIN_VALUE)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArray(sorted).insertionPointBefore(-1L)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArray(sorted).insertionPointAfter(0L)).isEqualTo(InsertionPoint.before(0)); } @Test public void binarySearch_inSortedLongArray_notFoundAtTheEnd() { long[] sorted = new long[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(41L)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(Long.MAX_VALUE)).isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedArray(sorted).insertionPointFor(50L)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArray(sorted).insertionPointBefore(Long.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArray(sorted).insertionPointAfter(Long.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedIntArray_withDuplicates() { int[] sorted = new int[] {10, 20, 20, 30, 40, 40, 40}; assertThat(inSortedArray(sorted).find(10)).hasValue(0); assertThat(inSortedArray(sorted).find(20).get()).isIn(ImmutableSet.of(1, 2)); assertThat(inSortedArray(sorted).rangeOf(20)).isEqualTo(Range.closed(1, 2)); assertThat(inSortedArray(sorted).insertionPointBefore(20)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(20)).isEqualTo(InsertionPoint.after(2)); assertThat(inSortedArray(sorted).rangeOf(40)).isEqualTo(Range.closed(4, 6)); assertThat(inSortedArray(sorted).insertionPointBefore(40)).isEqualTo(InsertionPoint.before(4)); assertThat(inSortedArray(sorted).insertionPointAfter(40)).isEqualTo(InsertionPoint.after(6)); } @Test public void binarySearch_inSortedLongArray_withDuplicates() { long[] sorted = new long[] {10, 20, 20, 30, 40, 40, 40}; assertThat(inSortedArray(sorted).find(10L)).hasValue(0); assertThat(inSortedArray(sorted).find(20L).get()).isIn(ImmutableSet.of(1, 2)); assertThat(inSortedArray(sorted).rangeOf(20L)).isEqualTo(Range.closed(1, 2)); assertThat(inSortedArray(sorted).insertionPointBefore(20L)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(20L)).isEqualTo(InsertionPoint.after(2)); assertThat(inSortedArray(sorted).rangeOf(40L)).isEqualTo(Range.closed(4, 6)); assertThat(inSortedArray(sorted).insertionPointBefore(40L)).isEqualTo(InsertionPoint.before(4)); assertThat(inSortedArray(sorted).insertionPointAfter(40L)).isEqualTo(InsertionPoint.after(6)); } @Test public void binarySearch_inSortedList_found() { ImmutableList<Integer> sorted = ImmutableList.of(10, 20, 30, 40); assertThat(inSortedList(sorted).find(20)).hasValue(1); assertThat(inSortedList(sorted).rangeOf(20)).isEqualTo(Range.closed(1, 1)); assertThat(inSortedList(sorted).insertionPointFor(20)).isEqualTo(InsertionPoint.at(1)); assertThat(inSortedList(sorted).insertionPointBefore(20)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedList(sorted).insertionPointAfter(20)).isEqualTo(InsertionPoint.after(1)); } @Test public void binarySearch_inSortedList_notFoundInTheMiddle() { ImmutableList<Integer> sorted = ImmutableList.of(10, 20, 30, 40); assertThat(inSortedList(sorted).find(19)).isEmpty(); assertThat(inSortedList(sorted).rangeOf(19)).isEqualTo(Range.closedOpen(1, 1)); assertThat(inSortedList(sorted).insertionPointFor(19)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedList(sorted).insertionPointBefore(19)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedList(sorted).insertionPointAfter(19)).isEqualTo(InsertionPoint.before(1)); } @Test public void binarySearch_inSortedList_notFoundAtTheBeginning() { ImmutableList<Integer> sorted = ImmutableList.of(10, 20, 30, 40); assertThat(inSortedList(sorted).find(-1)).isEmpty(); assertThat(inSortedList(sorted).rangeOf(-1)).isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedList(sorted).insertionPointFor(Integer.MIN_VALUE)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedList(sorted).insertionPointBefore(-1)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedList(sorted).insertionPointAfter(0)).isEqualTo(InsertionPoint.before(0)); } @Test public void binarySearch_inSortedList_notFoundAtTheEnd() { ImmutableList<Integer> sorted = ImmutableList.of(10, 20, 30, 40); assertThat(inSortedList(sorted).find(41)).isEmpty(); assertThat(inSortedList(sorted).rangeOf(Integer.MAX_VALUE)).isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedList(sorted).insertionPointFor(50)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedList(sorted).insertionPointBefore(Integer.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedList(sorted).insertionPointAfter(Integer.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedList_withDuplicates() { ImmutableList<Integer> sorted = ImmutableList.of(10, 20, 20, 30, 40, 40, 40); assertThat(inSortedList(sorted).find(10)).hasValue(0); assertThat(inSortedList(sorted).find(20).get()).isIn(ImmutableSet.of(1, 2)); assertThat(inSortedList(sorted).rangeOf(20)).isEqualTo(Range.closed(1, 2)); assertThat(inSortedList(sorted).insertionPointBefore(20)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedList(sorted).insertionPointAfter(20)).isEqualTo(InsertionPoint.after(2)); assertThat(inSortedList(sorted).rangeOf(40)).isEqualTo(Range.closed(4, 6)); assertThat(inSortedList(sorted).insertionPointBefore(40)).isEqualTo(InsertionPoint.before(4)); assertThat(inSortedList(sorted).insertionPointAfter(40)).isEqualTo(InsertionPoint.after(6)); } @Test public void binarySearch_inSortedList_byKeyFunction() { ImmutableList<String> sorted = ImmutableList.of("x", "ab", "foo", "zerg"); assertThat(inSortedList(sorted, String::length).find(2)).hasValue(1); } @Test public void binarySearch_inSortedList_byComparator() { List<String> sorted = asList(null, "a", "b", "c"); assertThat(inSortedList(sorted, Comparator.nullsFirst(Comparator.naturalOrder())).find(null)).hasValue(0); assertThat(inSortedList(sorted, Comparator.nullsFirst(Comparator.naturalOrder())).find("b")).hasValue(2); } @Test public void binarySearch_inSortedDoubleArrayWithTolerance_found() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, 0.9).find(20D)).hasValue(1); assertThat(inSortedArrayWithTolerance(sorted, 1).find(21D)).hasValue(1); assertThat(inSortedArrayWithTolerance(sorted, 1).find(19D)).hasValue(1); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(20D)).isEqualTo(Range.closed(1, 1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointFor(20D)).isEqualTo(InsertionPoint.at(1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(20D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(20D)).isEqualTo(InsertionPoint.after(1)); } @Test public void binarySearch_inSortedArrayWithTolerance_notFoundInTheMiddle() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, 1).find(18D)).isEmpty(); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(18D)).isEqualTo(Range.closedOpen(1, 1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointFor(18D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(18D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(18D)).isEqualTo(InsertionPoint.before(1)); } @Test public void binarySearch_inSortedArrayWithTolerance_notFoundAtTheBeginning() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, 1).find(-1D)).isEmpty(); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(-1D)).isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointFor(Double.MIN_VALUE)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointFor(Double.NEGATIVE_INFINITY)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(-1D)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(0D)).isEqualTo(InsertionPoint.before(0)); } @Test public void binarySearch_inSortedArrayWithTolerance_notFoundAtTheEnd() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, 1).find(42D)).isEmpty(); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(Double.MAX_VALUE)).isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointFor(50D)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(Double.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(Double.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArrayWithTolerance(sorted, 100).insertionPointFor(Double.NaN)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArrayWithTolerance(sorted, Double.MAX_VALUE).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArrayWithTolerance(sorted, Double.POSITIVE_INFINITY).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedArrayWithTolerance_withDuplicates() { double[] sorted = new double[] {10, 20.1, 20.2, 30, 40.1, 40.2, 40.3}; assertThat(inSortedArrayWithTolerance(sorted, 1).find(10D)).hasValue(0); assertThat(inSortedArrayWithTolerance(sorted, 1).find(20D).get()).isIn(ImmutableSet.of(1, 2)); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(20D)).isEqualTo(Range.closed(1, 2)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(20D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(20D)).isEqualTo(InsertionPoint.after(2)); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(40D)).isEqualTo(Range.closed(4, 6)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(40D)).isEqualTo(InsertionPoint.before(4)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(40D)).isEqualTo(InsertionPoint.after(6)); } @Test public void binarySearch_inSortedArrayWithTolerance_infinityTolerance() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(0D)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedArrayWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(Double.NEGATIVE_INFINITY)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedArrayWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(Double.POSITIVE_INFINITY)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedArrayWithTolerance(sorted, Double.POSITIVE_INFINITY).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedArrayWithTolerance_maxTolerance() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, Double.MAX_VALUE).rangeOf(0D)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedArrayWithTolerance(sorted, Double.MAX_VALUE).rangeOf(Double.NEGATIVE_INFINITY)) .isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedArrayWithTolerance(sorted, Double.MAX_VALUE).rangeOf(Double.POSITIVE_INFINITY)) .isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedArrayWithTolerance(sorted, Double.MAX_VALUE).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedArrayWithTolerance_invalidTolerance() { double[] sorted = new double[] {10, 20, 30, 40}; assertThrows(IllegalArgumentException.class, () -> inSortedArrayWithTolerance(sorted, -1)); assertThrows(IllegalArgumentException.class, () -> inSortedArrayWithTolerance(sorted, -Double.MAX_VALUE)); assertThrows(IllegalArgumentException.class, () -> inSortedArrayWithTolerance(sorted, Double.NEGATIVE_INFINITY)); assertThrows(IllegalArgumentException.class, () -> inSortedArrayWithTolerance(sorted, Double.NaN)); } @Test public void binarySearch_inSortedListWithTolerance_found() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, 0.9).find(20D)).hasValue(1); assertThat(inSortedListWithTolerance(sorted, 1).find(21D)).hasValue(1); assertThat(inSortedListWithTolerance(sorted, 1).find(19D)).hasValue(1); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(20D)).isEqualTo(Range.closed(1, 1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointFor(20D)).isEqualTo(InsertionPoint.at(1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(20D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(20D)).isEqualTo(InsertionPoint.after(1)); } @Test public void binarySearch_inSortedListWithTolerance_notFoundInTheMiddle() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, 1).find(18D)).isEmpty(); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(18D)).isEqualTo(Range.closedOpen(1, 1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointFor(18D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(18D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(18D)).isEqualTo(InsertionPoint.before(1)); } @Test public void binarySearch_inSortedListWithTolerance_notFoundAtTheBeginning() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, 1).find(-1D)).isEmpty(); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(-1D)).isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointFor(Double.MIN_VALUE)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointFor(Double.NEGATIVE_INFINITY)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(-1D)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(0D)).isEqualTo(InsertionPoint.before(0)); } @Test public void binarySearch_inSortedListWithTolerance_notFoundAtTheEnd() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, 1).find(42D)).isEmpty(); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(Double.MAX_VALUE)).isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointFor(50D)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(Double.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(Double.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedListWithTolerance(sorted, 100).insertionPointFor(Double.NaN)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedListWithTolerance(sorted, Double.MAX_VALUE).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); assertThat(inSortedListWithTolerance(sorted, Double.POSITIVE_INFINITY).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedListWithTolerance_withDuplicates() { ImmutableList<Double> sorted = ImmutableList.of(10.1, 20.1, 20.2, 30.1, 40.1, 40.2, 40.3); assertThat(inSortedListWithTolerance(sorted, 1).find(10D)).hasValue(0); assertThat(inSortedListWithTolerance(sorted, 1).find(20D).get()).isIn(ImmutableSet.of(1, 2)); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(20D)).isEqualTo(Range.closed(1, 2)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(20D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(20D)).isEqualTo(InsertionPoint.after(2)); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(40D)).isEqualTo(Range.closed(4, 6)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(40D)).isEqualTo(InsertionPoint.before(4)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(40D)).isEqualTo(InsertionPoint.after(6)); } @Test public void binarySearch_inSortedListWithTolerance_infinityTolerance() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(0D)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedListWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(Double.NEGATIVE_INFINITY)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedListWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(Double.POSITIVE_INFINITY)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedListWithTolerance(sorted, Double.POSITIVE_INFINITY).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedListWithTolerance_maxTolerance() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, Double.MAX_VALUE).rangeOf(0D)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedListWithTolerance(sorted, Double.MAX_VALUE).rangeOf(Double.NEGATIVE_INFINITY)) .isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedListWithTolerance(sorted, Double.MAX_VALUE).rangeOf(Double.POSITIVE_INFINITY)) .isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedListWithTolerance(sorted, Double.MAX_VALUE).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedListWithTolerance_invalidTolerance() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThrows(IllegalArgumentException.class, () -> inSortedListWithTolerance(sorted, -1)); assertThrows(IllegalArgumentException.class, () -> inSortedListWithTolerance(sorted, -Double.MAX_VALUE)); assertThrows(IllegalArgumentException.class, () -> inSortedListWithTolerance(sorted, Double.NEGATIVE_INFINITY)); assertThrows(IllegalArgumentException.class, () -> inSortedListWithTolerance(sorted, Double.NaN)); } @Test public void testNulls() throws Exception { new NullPointerTester().testAllPublicStaticMethods(BinarySearch.class); new ClassSanityTester().forAllPublicStaticMethods(BinarySearch.class).testNulls(); } @Test public void binarySearchIntSqrt_smallNumbers() { assertThat(intSqrt().insertionPointFor(4L).floor()).isEqualTo(2); assertThat(intSqrt().insertionPointFor(1L).floor()).isEqualTo(1); assertThat(intSqrt().insertionPointFor(0L).floor()).isEqualTo(0); assertThat(intSqrt().insertionPointFor(5L).floor()).isEqualTo(2); assertThat(intSqrt().insertionPointFor(101L).floor()).isEqualTo(10); assertThat(intSqrt().insertionPointFor(4097L).floor()).isEqualTo(64); } @Test public void binarySearchIntSqrt_largeNumbers() { int[] numbers = { Integer.MAX_VALUE, Integer.MAX_VALUE - 1, Integer.MAX_VALUE - 2, Integer.MAX_VALUE / 2, Integer.MAX_VALUE / 10 }; for (int n : numbers) { long square = ((long) n) * n; assertThat(intSqrt().insertionPointFor(square).floor()).isEqualTo(n); assertThat(intSqrt().insertionPointFor(square + 1).floor()).isEqualTo(n); assertThat(intSqrt().insertionPointFor(square - 1).floor()).isEqualTo(n - 1); assertThat(intSqrt().find(square)).hasValue(n); assertThat(intSqrt().find(square + 1)).isEmpty(); assertThat(intSqrt().find(square - 1)).isEmpty(); } } @Test public void binarySearchDoubleSqrt_smallNumbers( @TestParameter( {"0", "0.1", "0.2", "0.5", "1", "2", "3", "4", "5", "10", "20", "100", "1000", "9999999999"}) double square) { double epsilon = 0.0000000001; InsertionPoint<Double> insertionPoint = squareRoot().insertionPointFor(square); assertThat(insertionPoint.floor()).isWithin(epsilon).of(Math.sqrt(square)); assertThat(insertionPoint.ceiling()).isWithin(epsilon).of(Math.sqrt(square)); } @Test public void binarySearchDoubleCubeRoot_smallNumbers( @TestParameter( {"0", "0.1", "0.2", "0.5", "1", "2", "-3", "4", "5", "10", "-20", "100", "1000", "-9999.99999"}) double cube) { double epsilon = 0.0000000001; InsertionPoint<Double> insertionPoint = cubeRoot().insertionPointFor(cube); assertThat(insertionPoint.floor()).isWithin(epsilon).of(Math.cbrt(cube)); assertThat(insertionPoint.ceiling()).isWithin(epsilon).of(Math.cbrt(cube)); } @Test public void forDoubles_fullRange_smallNumberFound( @TestParameter( {"0", "0.1", "1", "100", "1000", "9999999999", "-1", "-100.345", "-999999.999"}) double secret) { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_fullRange_maxValueFound() { double secret = Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); assertThat(BinarySearch.forDoubles() .rangeOf((low, mid, high) -> Double.compare(secret, mid))) .isEqualTo(Range.closed(secret, secret)); } @Test public void forDoubles_fullRange_maxValueNotFound() { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> 1); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(Double.MAX_VALUE); assertThat(insertionPoint.ceiling()).isEqualTo(Double.POSITIVE_INFINITY); assertThat(BinarySearch.forDoubles().rangeOf(((low, mid, high) -> 1))) .isEqualTo(Range.closedOpen(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)); } @Test public void forDoubles_fullRange_minValueFound() { double secret = -Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); assertThat(BinarySearch.forDoubles() .rangeOf((low, mid, high) -> Double.compare(secret, mid))) .isEqualTo(Range.closed(secret, secret)); } @Test public void forDoubles_fullRange_minValueNotFound() { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> -1); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(Double.NEGATIVE_INFINITY); assertThat(insertionPoint.ceiling()).isEqualTo(-Double.MAX_VALUE); assertThat(BinarySearch.forDoubles().rangeOf(((low, mid, high) -> -1))) .isEqualTo(Range.closedOpen(-Double.MAX_VALUE, -Double.MAX_VALUE)); } @Test public void forDoubles_nonNegativeRange_smallNumberFound( @TestParameter( {"0", "0.1", "1", "100", "1000", "9999999999"}) double secret) { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.atLeast(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); assertThat(BinarySearch.forDoubles(Range.atLeast(0D)) .rangeOf((low, mid, high) -> Double.compare(secret, mid))) .isEqualTo(Range.closed(secret, secret)); } @Test public void forDoubles_positiveRange_smallNumberFound( @TestParameter( {"0.1", "1", "100", "1000", "9999999999"}) double secret) { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.greaterThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_positiveRange_maxValueFound() { double secret = Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.greaterThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_positiveRange_largeNumberFound() { double secret = Double.MAX_VALUE / Integer.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.greaterThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_positiveRange_maxValueNotFound() { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(greaterThan(0D)) .insertionPointFor((low, mid, high) -> 1); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(Double.MAX_VALUE); assertThat(insertionPoint.ceiling()).isEqualTo(Double.POSITIVE_INFINITY); } @Test public void forDoubles_positiveRange_invisibleNumber() { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(greaterThan(0D)) .insertionPointFor((low, mid, high) -> mid <= 100 ? 1 : -1); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(100.0); assertThat(insertionPoint.ceiling()).isEqualTo(Math.nextUp(100.0)); assertThat(BinarySearch.forDoubles(greaterThan(0D)) .rangeOf((low, mid, high) -> mid <= 100 ? 1 : -1)) .isEqualTo(Range.closedOpen(Math.nextUp(100.0), Math.nextUp(100.0))); } @Test public void forDoubles_singletonRange_maxValueFound() { double secret = Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.closed(secret, secret)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.exact()).hasValue(secret); } @Test public void forDoubles_singletonRange_maxValueNotFound() { double secret = Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.closed(secret, secret)) .insertionPointFor((low, mid, high) -> -1); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(Double.NEGATIVE_INFINITY); assertThat(insertionPoint.ceiling()).isEqualTo(Double.MAX_VALUE); } @Test public void forDoubles_singletonRange_minValueFound() { double secret = Double.MIN_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.closed(secret, secret)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.exact()).hasValue(secret); } @Test public void forDoubles_singletonRange_minValueNotFound() { double secret = Double.MIN_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.closed(secret, secret)) .insertionPointFor((low, mid, high) -> 1); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(Double.MIN_VALUE); assertThat(insertionPoint.ceiling()).isEqualTo(Double.POSITIVE_INFINITY); } @Test public void forDoubles_emptyRange( @TestParameter({"-1", "-0.5", "0", "0.1", "1", "100"}) double at) { assertThat(BinarySearch.forDoubles(Range.closedOpen(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.before(at)); assertThat(BinarySearch.forDoubles(Range.openClosed(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.after(at)); } @Test public void forDoubles_emptyRange_maxValue() { double at = Double.MAX_VALUE; assertThat(BinarySearch.forDoubles(Range.closedOpen(at, at)) .rangeOf((low, mid, high) -> 0)) .isEqualTo(Range.closedOpen(at, at)); assertThat(BinarySearch.forDoubles(Range.closedOpen(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.before(at)); assertThat(BinarySearch.forDoubles(Range.openClosed(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.after(at)); } @Test public void forDoubles_emptyRange_negativeMaxValue() { double at = -Double.MAX_VALUE; assertThat(BinarySearch.forDoubles(Range.closedOpen(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.before(at)); assertThat(BinarySearch.forDoubles(Range.openClosed(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.after(at)); } @Test public void forDoubles_emptyRange_infinityDisallowed() { assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(Range.closedOpen(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(Range.closedOpen(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(Range.openClosed(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(Range.openClosed(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY))); } @Test public void forDoubles_fullRange_infinityNotFound() { double secret = Double.POSITIVE_INFINITY; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(Double.MAX_VALUE); assertThat(insertionPoint.ceiling()).isEqualTo(Double.POSITIVE_INFINITY); } @Test public void forDoubles_fullRange_negativeInfinityNotFound() { double secret = Double.NEGATIVE_INFINITY; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.ceiling()).isEqualTo(-Double.MAX_VALUE); assertThat(insertionPoint.floor()).isEqualTo(Double.NEGATIVE_INFINITY); } @Test public void forDoubles_negativeRange_smallNumberFound( @TestParameter({"-1", "-100.345", "-999999.999"}) double secret) { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(lessThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_negativeRange_maxValueFound() { double secret = -Double.MIN_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(lessThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isWithin(2 * Double.MIN_NORMAL).of(secret); assertThat(insertionPoint.ceiling()).isWithin(2 * Double.MIN_NORMAL).of(secret); } @Test public void forDoubles_negativeRange_minValueFound() { double secret = -Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(lessThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_negativeRange_infinityNotFound() { double secret = Double.POSITIVE_INFINITY; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(lessThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(-Double.MIN_VALUE); assertThat(insertionPoint.ceiling()).isEqualTo(Double.POSITIVE_INFINITY); } @Test public void forDoubles_negativeRange_negativeInfinityNotFound() { double secret = Double.NEGATIVE_INFINITY; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(lessThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.ceiling()).isEqualTo(-Double.MAX_VALUE); assertThat(insertionPoint.floor()).isEqualTo(Double.NEGATIVE_INFINITY); } @Test public void forDoubles_infiniteRange_disallowed() { assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(closed(Double.NEGATIVE_INFINITY, 0D))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(closed(Double.NaN, 0D))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(closed(0D, Double.POSITIVE_INFINITY))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(closed(0D, Double.NaN))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(closed(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY))); } @Test public void binarySearchRotated_empty() { int[] sorted = {}; assertThat(inCircularSortedArray(sorted).find(1)).isEmpty(); } @Test public void binarySearchRotated_singleElement() { int[] sorted = {1}; assertThat(inCircularSortedArray(sorted).find(1)).hasValue(0); assertThat(inCircularSortedArray(sorted).find(2)).isEmpty(); } @Test public void binarySearchRotated_twoElements() { int[] sorted = {1, 2}; assertThat(inCircularSortedArray(sorted).find(1)).hasValue(0); assertThat(inCircularSortedArray(sorted).find(2)).hasValue(1); assertThat(inCircularSortedArray(sorted).find(3)).isEmpty(); } @Test public void binarySearchRotated_twoElementsReversed() { int[] sorted = {20, 10}; assertThat(inCircularSortedArray(sorted).find(10)).hasValue(1); assertThat(inCircularSortedArray(sorted).find(20)).hasValue(0); assertThat(inCircularSortedArray(sorted).find(30)).isEmpty(); } @Test public void binarySearchRotated_notRatated() { int[] sorted = {10, 20, 30, 40, 50, 60, 70}; for (int i = 0; i < sorted.length; i++) { assertThat(inCircularSortedArray(sorted).find(sorted[i])).hasValue(i); } assertThat(inCircularSortedArray(sorted).find(0)).isEmpty(); assertThat(inCircularSortedArray(sorted).find(80)).isEmpty(); assertThat(inCircularSortedArray(sorted).find(15)).isEmpty(); } @Test public void binarySearchRotated_ratated() { int[] rotated = {40, 50, 60, 70, 10, 20, 30}; for (int i = 0; i < rotated.length; i++) { assertThat(inCircularSortedArray(rotated).find(rotated[i])).hasValue(i); } assertThat(inCircularSortedArray(rotated).find(0)).isEmpty(); assertThat(inCircularSortedArray(rotated).find(80)).isEmpty(); assertThat(inCircularSortedArray(rotated).find(15)).isEmpty(); } @Test public void guessTheNumberGame( @TestParameter(valuesProvider = LongValues.class) long secret) { AtomicInteger times = new AtomicInteger(); assertThat(BinarySearch.forLongs().find((low, mid, high) -> { times.incrementAndGet(); return Long.compare(secret, mid); })).hasValue(secret); assertThat(times.get()).isAtMost(65); } @Test public void guessTheDoubleNumberGame( @TestParameter(valuesProvider = DoubleValues.class) double secret) { AtomicInteger times = new AtomicInteger(); ImmutableMap.Builder<Double, Integer> builder = ImmutableMap.builder(); assertThat(BinarySearch.forDoubles().find((low, mid, high) -> { builder.put(mid, times.incrementAndGet()); return Double.compare(secret, mid); })).hasValue(secret); assertThat(builder.buildOrThrow().size()).isAtMost(65); assertThat(times.get()).isAtMost(65); } @Test public void guessTheDoubleNumberWithMostlyPositive( @TestParameter({"-0.5", "-0.1", "0", "0.001", "0.1", "1"}) double secret) { AtomicInteger times = new AtomicInteger(); ImmutableMap.Builder<Double, Integer> builder = ImmutableMap.builder(); assertThat(BinarySearch.forDoubles(atLeast(-1.0)).find((low, mid, high) -> { builder.put(mid, times.incrementAndGet()); return Double.compare(secret, mid); })).hasValue(secret); assertThat(builder.buildOrThrow().size()).isAtMost(65); assertThat(times.get()).isAtMost(65); } @Test public void binarySearch_findMinParabola() { InsertionPoint<Integer> point = BinarySearch.forInts() .insertionPointFor((low, mid, high) -> Double.compare(parabola(mid - 1), parabola(mid))); int solution = point.floor(); assertThat(solution).isEqualTo(-2); } private static double parabola(int x) { return Math.pow(x, 2) + 4 * x - 3; } // Demo how binarySearch() can be used to implement more advanced binary search algorithms // such as searching within a rotated array. private static BinarySearch<Integer, Integer> inCircularSortedArray(int[] rotated) { return BinarySearch.forInts(Range.closedOpen(0, rotated.length)) .by(key -> (low, mid, high) -> { int probe = rotated[mid]; if (key < probe) { // target < mid value. // [low] <= probe means we are in the left half of [4, 5, 6, 1, 2, 3]. // If we are in the first ascending half, it's in the right side if key < // rotated[lower]. // If we are in the second ascending half, the right half is useless. Look left. return rotated[low] <= probe && key < rotated[low] ? 1 : -1; } else if (key > probe) { // key > mid value. // probe <= [high] means we are in the right half of [4, 5, 6, 1, 2, 3]. // If we are in the second ascending half, it's in the left side if key > // rotated[high]. // If we are in the first ascending half, the left side is useless. Look right. return probe <= rotated[high] && key > rotated[high] ? -1 : 1; } else { return 0; } }); } private static BinarySearch<Long, Integer> intSqrt() { return BinarySearch.forInts(atLeast(0)) .by(square -> (low, mid, high) -> Long.compare(square, (long) mid * mid)); } private static BinarySearch<Double, Double> squareRoot() { return BinarySearch.forDoubles(atLeast(0D)) .by(square -> (low, mid, high) -> Double.compare(square, mid * mid)); } private static BinarySearch<Double, Double> cubeRoot() { return BinarySearch.forDoubles() .by(cube -> (low, mid, high) -> Double.compare(cube, mid * mid * mid)); } static class NegativeValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.of( Integer.MIN_VALUE, Integer.MIN_VALUE + 1, Integer.MIN_VALUE / 2, Integer.MIN_VALUE / 3, -3, -2, -1); } } static class NegativeLongValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.of( Long.MIN_VALUE, Long.MIN_VALUE + 1, Long.MIN_VALUE / 2, Long.MIN_VALUE / 3, -3L, -2L, -1L); } } static class NonNegativeValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.of( 0, 1, 2, 3, Integer.MAX_VALUE, Integer.MAX_VALUE - 1, Integer.MAX_VALUE - 2, Integer.MAX_VALUE - 3, Integer.MAX_VALUE / 2, Integer.MAX_VALUE / 3); } } static class NonNegativeLongValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.of( 0L, 1L, 2L, 3L, Long.MAX_VALUE, Long.MAX_VALUE - 1, Long.MAX_VALUE - 2, Long.MAX_VALUE - 3, Long.MAX_VALUE / 2, Long.MAX_VALUE / 3); } } static class IntValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.builder() .addAll(new NegativeValues().provideValues()) .addAll(new NonNegativeValues().provideValues()) .build(); } } static class LongValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.builder() .addAll(new NegativeLongValues().provideValues()) .addAll(new NonNegativeLongValues().provideValues()) .build(); } } static class DoubleValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.of( -Long.MAX_VALUE, -Long.MAX_VALUE / 2, -Long.MAX_VALUE / 3, -3D, -2.5D, -1D, 0D, 0.5, 0.123456789, 1D, 2D, 3D, Double.MAX_VALUE, Double.MAX_VALUE / 2, Double.MAX_VALUE / 3); } } }
mug-guava/src/test/java/com/google/mu/util/BinarySearchTest.java
package com.google.mu.util; import static com.google.common.collect.Range.atLeast; import static com.google.common.collect.Range.atMost; import static com.google.common.collect.Range.closed; import static com.google.common.collect.Range.closedOpen; import static com.google.common.collect.Range.greaterThan; import static com.google.common.collect.Range.lessThan; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static com.google.mu.util.BinarySearch.inSortedArray; import static com.google.mu.util.BinarySearch.inSortedArrayWithTolerance; import static com.google.mu.util.BinarySearch.inSortedList; import static com.google.mu.util.BinarySearch.inSortedListWithTolerance; import static java.util.Arrays.asList; import static org.junit.Assert.assertThrows; import java.util.Comparator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Range; import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester; import com.google.common.truth.Expect; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; @RunWith(TestParameterInjector.class) public class BinarySearchTest { @Rule public final Expect expect = Expect.create(); @Test public void inRangeInclusive_invalidIndex() { assertThrows(IllegalArgumentException.class, () -> BinarySearch.forInts(closed(2, 0))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forInts(closed(Integer.MAX_VALUE, Integer.MAX_VALUE - 2))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forInts(closed(Integer.MIN_VALUE + 2, Integer.MIN_VALUE))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forInts(closed(Integer.MAX_VALUE, Integer.MIN_VALUE))); } @Test public void forLongs_Inclusive_invalidIndex() { assertThrows(IllegalArgumentException.class, () -> BinarySearch.forLongs(closed(2L, 0L))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forLongs(closed(Long.MAX_VALUE, Long.MAX_VALUE - 2))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forLongs(closed(Long.MIN_VALUE + 2, Long.MIN_VALUE))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forLongs(closed(Long.MAX_VALUE, Long.MIN_VALUE))); } @Test public void forInts_empty() { assertThat(BinarySearch.forInts(closedOpen(0, 0)).find((l, i, h) -> 0)).isEmpty(); assertThat(BinarySearch.forInts(closedOpen(0, 0)).rangeOf((l, i, h) -> 0)) .isEqualTo(Range.closedOpen(0, 0)); assertThat(BinarySearch.forInts(closedOpen(0, 0)).insertionPointFor((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(closedOpen(0, 0)).insertionPointBefore((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(closedOpen(0, 0)).insertionPointAfter((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(greaterThan(Integer.MAX_VALUE)).rangeOf((l, i, h) -> 0)) .isEqualTo(Range.closedOpen(Integer.MAX_VALUE, Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(greaterThan(Integer.MAX_VALUE)).find((l, i, h) -> 0)) .isEmpty(); assertThat(BinarySearch.forInts(lessThan(Integer.MIN_VALUE)).find((l, i, h) -> 0)) .isEmpty(); } @Test public void forLongs_empty() { assertThat(BinarySearch.forLongs(closedOpen(0L, 0L)).find((l, i, h) -> 0)).isEmpty(); assertThat(BinarySearch.forLongs(closedOpen(0L, 0L)).rangeOf((l, i, h) -> 0)) .isEqualTo(Range.closedOpen(0L, 0L)); assertThat(BinarySearch.forLongs(closedOpen(0L, 0L)).insertionPointFor((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0L)); assertThat(BinarySearch.forLongs(closedOpen(0L, 0L)).insertionPointBefore((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0L)); assertThat(BinarySearch.forLongs(closedOpen(0L, 0L)).insertionPointAfter((l, i, h) -> 0)) .isEqualTo(InsertionPoint.before(0L)); assertThat(BinarySearch.forLongs(greaterThan(Long.MAX_VALUE)).rangeOf((l, i, h) -> 0)) .isEqualTo(Range.closedOpen(Long.MAX_VALUE, Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(greaterThan(Long.MAX_VALUE)).find((l, i, h) -> 0)) .isEmpty(); assertThat(BinarySearch.forLongs(lessThan(Long.MIN_VALUE)).find((l, i, h) -> 0)) .isEmpty(); } @Test public void forInts_singleCandidateRange_found() { assertThat(BinarySearch.forInts(closed(1, 1)).find((l, i, h) -> Integer.compare(i, 1))) .hasValue(1); assertThat(BinarySearch.forInts(closed(1, 1)).rangeOf((l, i, h) -> Integer.compare(i, 1))) .isEqualTo(Range.closed(1, 1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointFor((l, i, h) -> Integer.compare(i, 1))) .isEqualTo(InsertionPoint.at(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointBefore((l, i, h) -> Integer.compare(i, 1))) .isEqualTo(InsertionPoint.before(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointAfter((l, i, h) -> Integer.compare(i, 1))) .isEqualTo(InsertionPoint.after(1)); } @Test public void forLongs_singleCandidateRange_found() { assertThat(BinarySearch.forLongs(closed(1L, 1L)).find((l, i, h) -> Long.compare(i, 1))) .hasValue(1L); assertThat(BinarySearch.forLongs(closed(1L, 1L)).rangeOf((l, i, h) -> Long.compare(i, 1))) .isEqualTo(Range.closed(1L, 1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointFor((l, i, h) -> Long.compare(i, 1))) .isEqualTo(InsertionPoint.at(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointBefore((l, i, h) -> Long.compare(i, 1))) .isEqualTo(InsertionPoint.before(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointAfter((l, i, h) -> Long.compare(i, 1))) .isEqualTo(InsertionPoint.after(1L)); } @Test public void forInts_singleCandidateRange_shouldBeBefore() { assertThat(BinarySearch.forInts(closed(1, 1)).find((l, i, h) -> Integer.compare(0, i))) .isEmpty(); assertThat(BinarySearch.forInts(closed(1, 1)).rangeOf((l, i, h) -> Integer.compare(0, i))) .isEqualTo(Range.closedOpen(1, 1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointFor((l, i, h) -> Integer.compare(0, i))) .isEqualTo(InsertionPoint.before(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointBefore((l, i, h) -> Integer.compare(0, i))) .isEqualTo(InsertionPoint.before(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointAfter((l, i, h) -> Integer.compare(0, i))) .isEqualTo(InsertionPoint.before(1)); } @Test public void forInts_singleCandidateRange_shouldBeAfter() { assertThat(BinarySearch.forInts(closed(1, 1)).find((l, i, h) -> Integer.compare(10, i))) .isEmpty(); assertThat(BinarySearch.forInts(closed(1, 1)).rangeOf((l, i, h) -> Integer.compare(10, i))) .isEqualTo(Range.closedOpen(2, 2)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointFor((l, i, h) -> Integer.compare(10, i))) .isEqualTo(InsertionPoint.after(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointBefore((l, i, h) -> Integer.compare(10, i))) .isEqualTo(InsertionPoint.after(1)); assertThat(BinarySearch.forInts(closed(1, 1)).insertionPointAfter((l, i, h) -> Integer.compare(10, i))) .isEqualTo(InsertionPoint.after(1)); } @Test public void forLongs_singleCandidateRange_shouldBeBefore() { assertThat(BinarySearch.forLongs(closed(1L, 1L)).find((l, i, h) -> Long.compare(0, i))) .isEmpty(); assertThat(BinarySearch.forLongs(closed(1L, 1L)).rangeOf((l, i, h) -> Long.compare(0, i))) .isEqualTo(Range.closedOpen(1L, 1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointFor((l, i, h) -> Long.compare(0, i))) .isEqualTo(InsertionPoint.before(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointBefore((l, i, h) -> Long.compare(0, i))) .isEqualTo(InsertionPoint.before(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointAfter((l, i, h) -> Long.compare(0, i))) .isEqualTo(InsertionPoint.before(1L)); } @Test public void forLongs_singleCandidateRange_shouldBeAfter() { assertThat(BinarySearch.forLongs(closed(1L, 1L)).find((l, i, h) -> Long.compare(3, i))) .isEmpty(); assertThat(BinarySearch.forLongs(closed(1L, 1L)).rangeOf((l, i, h) -> Long.compare(3, i))) .isEqualTo(Range.closedOpen(2L, 2L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointFor((l, i, h) -> Long.compare(3, i))) .isEqualTo(InsertionPoint.after(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointBefore((l, i, h) -> Long.compare(3, i))) .isEqualTo(InsertionPoint.after(1L)); assertThat(BinarySearch.forLongs(closed(1L, 1L)).insertionPointAfter((l, i, h) -> Long.compare(3, i))) .isEqualTo(InsertionPoint.after(1L)); } @Test public void forInts_useMinValueForLeft() { assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).find((l, i, h) -> Integer.MIN_VALUE)) .isEmpty(); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).rangeOf((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(Range.closedOpen(Integer.MIN_VALUE, Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointFor((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointBefore((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointAfter((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); } @Test public void forInts_preventsUderflow_shouldBeBefore() { assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Integer.MIN_VALUE, Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); } @Test public void forInts_useMaxValueForRight() { assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).find((l, i, h) -> Integer.MAX_VALUE)) .isEmpty(); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).rangeOf((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(Range.closedOpen(Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 1)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointFor((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointBefore((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointAfter((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); } @Test public void forInts_preventsUnderflow_shouldBeAfter() { assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.closedOpen(Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 1)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts(atMost(Integer.MIN_VALUE)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MIN_VALUE)); } @Test public void forLongs_useMinValueForLeft() { assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).find((l, i, h) -> Integer.MIN_VALUE)) .isEmpty(); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).rangeOf((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE, Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointFor((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointBefore((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointAfter((l, i, h) -> Integer.MIN_VALUE)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); } @Test public void forLongs_preventsUderflow_shouldBeBefore() { assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE, Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); } @Test public void forLongs_useMaxValueForRight() { assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).find((l, i, h) -> Integer.MAX_VALUE)) .isEmpty(); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).rangeOf((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE + 1, Long.MIN_VALUE + 1)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointFor((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointBefore((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointAfter((l, i, h) -> Integer.MAX_VALUE)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); } @Test public void forLongs_preventsUnderflow_shouldBeAfter() { assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE + 1, Long.MIN_VALUE + 1)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(atMost(Long.MIN_VALUE)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MIN_VALUE)); } @Test public void forInts_preventsOverflow_shouldBeBefore() { assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Integer.MAX_VALUE, Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MAX_VALUE)); } @Test public void forInts_preventsOverflow_shouldBeAfter() { assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Integer.MAX_VALUE, Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(Integer.MAX_VALUE)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); } @Test public void forLongs_preventsOverflow_shouldBeBefore() { assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Long.MAX_VALUE, Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MAX_VALUE)); } @Test public void forLongs_preventsOverflow_shouldBeAfter() { assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Long.MAX_VALUE, Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(Long.MAX_VALUE)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); } @Test public void forInts_maxRange_shouldBeBefore() { assertThat(BinarySearch.forInts().find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forInts().rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Integer.MIN_VALUE, Integer.MIN_VALUE)); assertThat(BinarySearch.forInts().insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts().insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); assertThat(BinarySearch.forInts().insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Integer.MIN_VALUE)); } @Test public void forInts_maxRange_shouldBeAfter() { assertThat(BinarySearch.forInts().find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forInts().rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Integer.MAX_VALUE, Integer.MAX_VALUE)); assertThat(BinarySearch.forInts().insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts().insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts().insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); } @Test public void forLongs_maxRange_shouldBeBefore() { assertThat(BinarySearch.forLongs().find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forLongs().rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE, Long.MIN_VALUE)); assertThat(BinarySearch.forLongs().insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs().insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs().insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); } @Test public void forLongs_maxRange_shouldBeAfter() { assertThat(BinarySearch.forLongs().find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forLongs().rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Long.MAX_VALUE, Long.MAX_VALUE)); assertThat(BinarySearch.forLongs().insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs().insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs().insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); } @Test public void forInts_maxPositiveRange_shouldBeBefore() { assertThat(BinarySearch.forInts(atLeast(0)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forInts(atLeast(0)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(0, 0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(0)); } @Test public void forInts_maxPositiveRange_shouldBeAfter() { assertThat(BinarySearch.forInts(atLeast(0)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forInts(atLeast(0)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Integer.MAX_VALUE, Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Integer.MAX_VALUE)); } @Test public void forLongs_maxPositiveRange_shouldBeAfter() { assertThat(BinarySearch.forLongs(atLeast(0L)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forLongs(atLeast(0L)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.openClosed(Long.MAX_VALUE, Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(Long.MAX_VALUE)); } @Test public void forInts_maxNegativeRange_shouldBeAfter() { assertThat(BinarySearch.forInts(Range.lessThan(0)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forInts(Range.lessThan(0)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.closedOpen(0, 0)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1)); } @Test public void forLongs_maxNegativeRange_shouldBeBefore() { assertThat(BinarySearch.forLongs(Range.lessThan(0L)).find((l, i, h) -> -1)) .isEmpty(); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).rangeOf((l, i, h) -> -1)) .isEqualTo(Range.closedOpen(Long.MIN_VALUE, Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointFor((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointBefore((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointAfter((l, i, h) -> -1)) .isEqualTo(InsertionPoint.before(Long.MIN_VALUE)); } @Test public void forLongs_maxNegativeRange_shouldBeAfter() { assertThat(BinarySearch.forLongs(Range.lessThan(0L)).find((l, i, h) -> 1)) .isEmpty(); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).rangeOf((l, i, h) -> 1)) .isEqualTo(Range.closedOpen(0L, 0L)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointFor((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1L)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointBefore((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1L)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointAfter((l, i, h) -> 1)) .isEqualTo(InsertionPoint.after(-1L)); } @Test public void forInts_maxRange_found( @TestParameter(valuesProvider = IntValues.class) int target) { assertThat( BinarySearch.forInts(Range.<Integer>all()) .find((l, i, h) -> Integer.compare(target, i))) .hasValue(target); assertThat( BinarySearch.forInts(Range.<Integer>all()) .rangeOf((l, i, h) -> Integer.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat( BinarySearch.forInts(Range.<Integer>all()) .insertionPointFor((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat( BinarySearch.forInts(Range.<Integer>all()) .insertionPointBefore((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat( BinarySearch.forInts(Range.<Integer>all()) .insertionPointAfter((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forInts_maxNegativeRange_found( @TestParameter(valuesProvider = NegativeValues.class) int target) { assertThat(BinarySearch.forInts(Range.lessThan(0)).find((l, i, h) -> Integer.compare(target, i))) .hasValue(target); assertThat(BinarySearch.forInts(Range.lessThan(0)).rangeOf((l, i, h) -> Integer.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointFor((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointBefore((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat(BinarySearch.forInts(Range.lessThan(0)).insertionPointAfter((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forLongs_maxRange_found( @TestParameter(valuesProvider = LongValues.class) long target) { assertThat( BinarySearch.forLongs(Range.<Long>all()) .find((l, i, h) -> Long.compare(target, i))) .hasValue(target); assertThat( BinarySearch.forLongs(Range.<Long>all()) .rangeOf((l, i, h) -> Long.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat( BinarySearch.forLongs(Range.<Long>all()) .insertionPointFor((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat( BinarySearch.forLongs(Range.<Long>all()) .insertionPointBefore((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat( BinarySearch.forLongs(Range.<Long>all()) .insertionPointAfter((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forLongs_maxNegativeRange_found( @TestParameter(valuesProvider = NegativeLongValues.class) long target) { assertThat(BinarySearch.forLongs(Range.lessThan(0L)).find((l, i, h) -> Long.compare(target, i))) .hasValue(target); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).rangeOf((l, i, h) -> Long.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointFor((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointBefore((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat(BinarySearch.forLongs(Range.lessThan(0L)).insertionPointAfter((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forInts_maxNonNegativeRange_found( @TestParameter(valuesProvider = NonNegativeValues.class) int target) { assertThat(BinarySearch.forInts(atLeast(0)).find((l, i, h) -> Integer.compare(target, i))) .hasValue(target); assertThat(BinarySearch.forInts(atLeast(0)).rangeOf((l, i, h) -> Integer.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointFor((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointBefore((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointAfter((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forLongs_maxNonNegativeRange_found( @TestParameter(valuesProvider = NonNegativeLongValues.class) long target) { assertThat(BinarySearch.forLongs(atLeast(0L)).find((l, i, h) -> Long.compare(target, i))) .hasValue(target); assertThat(BinarySearch.forLongs(atLeast(0L)).rangeOf((l, i, h) -> Long.compare(target, i))) .isEqualTo(Range.closed(target, target)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointFor((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.at(target)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointBefore((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(target)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointAfter((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.after(target)); } @Test public void forInts_maxNonNegativeRange_negativeNotFound( @TestParameter(valuesProvider = NegativeValues.class) int target) { assertThat(BinarySearch.forInts(atLeast(0)).find((l, i, h) -> Integer.compare(target, i))) .isEmpty(); assertThat(BinarySearch.forInts(atLeast(0)).rangeOf((l, i, h) -> Integer.compare(target, i))) .isEqualTo(Range.closedOpen(0, 0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointFor((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointBefore((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(0)); assertThat(BinarySearch.forInts(atLeast(0)).insertionPointAfter((l, i, h) -> Integer.compare(target, i))) .isEqualTo(InsertionPoint.before(0)); } @Test public void forLongs_maxNonNegativeRange_negativeNotFound( @TestParameter(valuesProvider = NegativeValues.class) int target) { assertThat(BinarySearch.forLongs(atLeast(0L)).find((l, i, h) -> Long.compare(target, i))) .isEmpty(); assertThat(BinarySearch.forLongs(atLeast(0L)).rangeOf((l, i, h) -> Long.compare(target, i))) .isEqualTo(Range.closedOpen(0L, 0L)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointFor((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(0L)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointBefore((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(0L)); assertThat(BinarySearch.forLongs(atLeast(0L)).insertionPointAfter((l, i, h) -> Long.compare(target, i))) .isEqualTo(InsertionPoint.before(0L)); } @Test public void binarySearch_inSortedIntArray_found() { int[] sorted = new int[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(20)).hasValue(1); assertThat(inSortedArray(sorted).rangeOf(20)).isEqualTo(Range.closed(1, 1)); assertThat(inSortedArray(sorted).insertionPointFor(20)).isEqualTo(InsertionPoint.at(1)); assertThat(inSortedArray(sorted).insertionPointBefore(20)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(20)).isEqualTo(InsertionPoint.after(1)); } @Test public void binarySearch_inSortedIntArray_notFoundInTheMiddle() { int[] sorted = new int[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(19)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(19)).isEqualTo(Range.closedOpen(1, 1)); assertThat(inSortedArray(sorted).insertionPointFor(19)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointBefore(19)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(19)).isEqualTo(InsertionPoint.before(1)); } @Test public void binarySearch_inSortedIntArray_notFoundAtTheBeginning() { int[] sorted = new int[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(-1)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(-1)).isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedArray(sorted).insertionPointFor(Integer.MIN_VALUE)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArray(sorted).insertionPointBefore(-1)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArray(sorted).insertionPointAfter(0)).isEqualTo(InsertionPoint.before(0)); } @Test public void binarySearch_inSortedIntArray_notFoundAtTheEnd() { int[] sorted = new int[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(41)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(Integer.MAX_VALUE)).isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedArray(sorted).insertionPointFor(50)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArray(sorted).insertionPointBefore(Integer.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArray(sorted).insertionPointAfter(Integer.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedLongArray_found() { long[] sorted = new long[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(20L)).hasValue(1); assertThat(inSortedArray(sorted).rangeOf(20L)).isEqualTo(Range.closed(1, 1)); assertThat(inSortedArray(sorted).insertionPointFor(20L)).isEqualTo(InsertionPoint.at(1)); assertThat(inSortedArray(sorted).insertionPointBefore(20L)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(20L)).isEqualTo(InsertionPoint.after(1)); } @Test public void binarySearch_inSortedLongArray_notFoundInTheMiddle() { long[] sorted = new long[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(19L)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(19L)).isEqualTo(Range.closedOpen(1, 1)); assertThat(inSortedArray(sorted).insertionPointFor(19L)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointBefore(19L)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(19L)).isEqualTo(InsertionPoint.before(1)); } @Test public void binarySearch_inSortedLongArray_notFoundAtTheBeginning() { long[] sorted = new long[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(-1L)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(-1L)).isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedArray(sorted).insertionPointFor(Long.MIN_VALUE)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArray(sorted).insertionPointBefore(-1L)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArray(sorted).insertionPointAfter(0L)).isEqualTo(InsertionPoint.before(0)); } @Test public void binarySearch_inSortedLongArray_notFoundAtTheEnd() { long[] sorted = new long[] {10, 20, 30, 40}; assertThat(inSortedArray(sorted).find(41L)).isEmpty(); assertThat(inSortedArray(sorted).rangeOf(Long.MAX_VALUE)).isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedArray(sorted).insertionPointFor(50L)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArray(sorted).insertionPointBefore(Long.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArray(sorted).insertionPointAfter(Long.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedIntArray_withDuplicates() { int[] sorted = new int[] {10, 20, 20, 30, 40, 40, 40}; assertThat(inSortedArray(sorted).find(10)).hasValue(0); assertThat(inSortedArray(sorted).find(20).get()).isIn(ImmutableSet.of(1, 2)); assertThat(inSortedArray(sorted).rangeOf(20)).isEqualTo(Range.closed(1, 2)); assertThat(inSortedArray(sorted).insertionPointBefore(20)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(20)).isEqualTo(InsertionPoint.after(2)); assertThat(inSortedArray(sorted).rangeOf(40)).isEqualTo(Range.closed(4, 6)); assertThat(inSortedArray(sorted).insertionPointBefore(40)).isEqualTo(InsertionPoint.before(4)); assertThat(inSortedArray(sorted).insertionPointAfter(40)).isEqualTo(InsertionPoint.after(6)); } @Test public void binarySearch_inSortedLongArray_withDuplicates() { long[] sorted = new long[] {10, 20, 20, 30, 40, 40, 40}; assertThat(inSortedArray(sorted).find(10L)).hasValue(0); assertThat(inSortedArray(sorted).find(20L).get()).isIn(ImmutableSet.of(1, 2)); assertThat(inSortedArray(sorted).rangeOf(20L)).isEqualTo(Range.closed(1, 2)); assertThat(inSortedArray(sorted).insertionPointBefore(20L)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArray(sorted).insertionPointAfter(20L)).isEqualTo(InsertionPoint.after(2)); assertThat(inSortedArray(sorted).rangeOf(40L)).isEqualTo(Range.closed(4, 6)); assertThat(inSortedArray(sorted).insertionPointBefore(40L)).isEqualTo(InsertionPoint.before(4)); assertThat(inSortedArray(sorted).insertionPointAfter(40L)).isEqualTo(InsertionPoint.after(6)); } @Test public void binarySearch_inSortedList_found() { ImmutableList<Integer> sorted = ImmutableList.of(10, 20, 30, 40); assertThat(inSortedList(sorted).find(20)).hasValue(1); assertThat(inSortedList(sorted).rangeOf(20)).isEqualTo(Range.closed(1, 1)); assertThat(inSortedList(sorted).insertionPointFor(20)).isEqualTo(InsertionPoint.at(1)); assertThat(inSortedList(sorted).insertionPointBefore(20)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedList(sorted).insertionPointAfter(20)).isEqualTo(InsertionPoint.after(1)); } @Test public void binarySearch_inSortedList_notFoundInTheMiddle() { ImmutableList<Integer> sorted = ImmutableList.of(10, 20, 30, 40); assertThat(inSortedList(sorted).find(19)).isEmpty(); assertThat(inSortedList(sorted).rangeOf(19)).isEqualTo(Range.closedOpen(1, 1)); assertThat(inSortedList(sorted).insertionPointFor(19)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedList(sorted).insertionPointBefore(19)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedList(sorted).insertionPointAfter(19)).isEqualTo(InsertionPoint.before(1)); } @Test public void binarySearch_inSortedList_notFoundAtTheBeginning() { ImmutableList<Integer> sorted = ImmutableList.of(10, 20, 30, 40); assertThat(inSortedList(sorted).find(-1)).isEmpty(); assertThat(inSortedList(sorted).rangeOf(-1)).isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedList(sorted).insertionPointFor(Integer.MIN_VALUE)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedList(sorted).insertionPointBefore(-1)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedList(sorted).insertionPointAfter(0)).isEqualTo(InsertionPoint.before(0)); } @Test public void binarySearch_inSortedList_notFoundAtTheEnd() { ImmutableList<Integer> sorted = ImmutableList.of(10, 20, 30, 40); assertThat(inSortedList(sorted).find(41)).isEmpty(); assertThat(inSortedList(sorted).rangeOf(Integer.MAX_VALUE)).isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedList(sorted).insertionPointFor(50)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedList(sorted).insertionPointBefore(Integer.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedList(sorted).insertionPointAfter(Integer.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedList_withDuplicates() { ImmutableList<Integer> sorted = ImmutableList.of(10, 20, 20, 30, 40, 40, 40); assertThat(inSortedList(sorted).find(10)).hasValue(0); assertThat(inSortedList(sorted).find(20).get()).isIn(ImmutableSet.of(1, 2)); assertThat(inSortedList(sorted).rangeOf(20)).isEqualTo(Range.closed(1, 2)); assertThat(inSortedList(sorted).insertionPointBefore(20)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedList(sorted).insertionPointAfter(20)).isEqualTo(InsertionPoint.after(2)); assertThat(inSortedList(sorted).rangeOf(40)).isEqualTo(Range.closed(4, 6)); assertThat(inSortedList(sorted).insertionPointBefore(40)).isEqualTo(InsertionPoint.before(4)); assertThat(inSortedList(sorted).insertionPointAfter(40)).isEqualTo(InsertionPoint.after(6)); } @Test public void binarySearch_inSortedList_byKeyFunction() { ImmutableList<String> sorted = ImmutableList.of("x", "ab", "foo", "zerg"); assertThat(inSortedList(sorted, String::length).find(2)).hasValue(1); } @Test public void binarySearch_inSortedList_byComparator() { List<String> sorted = asList(null, "a", "b", "c"); assertThat(inSortedList(sorted, Comparator.nullsFirst(Comparator.naturalOrder())).find(null)).hasValue(0); assertThat(inSortedList(sorted, Comparator.nullsFirst(Comparator.naturalOrder())).find("b")).hasValue(2); } @Test public void binarySearch_inSortedDoubleArrayWithTolerance_found() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, 0.9).find(20D)).hasValue(1); assertThat(inSortedArrayWithTolerance(sorted, 1).find(21D)).hasValue(1); assertThat(inSortedArrayWithTolerance(sorted, 1).find(19D)).hasValue(1); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(20D)).isEqualTo(Range.closed(1, 1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointFor(20D)).isEqualTo(InsertionPoint.at(1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(20D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(20D)).isEqualTo(InsertionPoint.after(1)); } @Test public void binarySearch_inSortedArrayWithTolerance_notFoundInTheMiddle() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, 1).find(18D)).isEmpty(); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(18D)).isEqualTo(Range.closedOpen(1, 1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointFor(18D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(18D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(18D)).isEqualTo(InsertionPoint.before(1)); } @Test public void binarySearch_inSortedArrayWithTolerance_notFoundAtTheBeginning() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, 1).find(-1D)).isEmpty(); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(-1D)).isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointFor(Double.MIN_VALUE)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointFor(Double.NEGATIVE_INFINITY)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(-1D)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(0D)).isEqualTo(InsertionPoint.before(0)); } @Test public void binarySearch_inSortedArrayWithTolerance_notFoundAtTheEnd() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, 1).find(42D)).isEmpty(); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(Double.MAX_VALUE)).isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointFor(50D)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(Double.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(Double.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArrayWithTolerance(sorted, 100).insertionPointFor(Double.NaN)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArrayWithTolerance(sorted, Double.MAX_VALUE).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); assertThat(inSortedArrayWithTolerance(sorted, Double.POSITIVE_INFINITY).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedArrayWithTolerance_withDuplicates() { double[] sorted = new double[] {10, 20.1, 20.2, 30, 40.1, 40.2, 40.3}; assertThat(inSortedArrayWithTolerance(sorted, 1).find(10D)).hasValue(0); assertThat(inSortedArrayWithTolerance(sorted, 1).find(20D).get()).isIn(ImmutableSet.of(1, 2)); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(20D)).isEqualTo(Range.closed(1, 2)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(20D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(20D)).isEqualTo(InsertionPoint.after(2)); assertThat(inSortedArrayWithTolerance(sorted, 1).rangeOf(40D)).isEqualTo(Range.closed(4, 6)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointBefore(40D)).isEqualTo(InsertionPoint.before(4)); assertThat(inSortedArrayWithTolerance(sorted, 1).insertionPointAfter(40D)).isEqualTo(InsertionPoint.after(6)); } @Test public void binarySearch_inSortedArrayWithTolerance_infinityTolerance() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(0D)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedArrayWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(Double.NEGATIVE_INFINITY)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedArrayWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(Double.POSITIVE_INFINITY)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedArrayWithTolerance(sorted, Double.POSITIVE_INFINITY).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedArrayWithTolerance_maxTolerance() { double[] sorted = new double[] {10, 20, 30, 40}; assertThat(inSortedArrayWithTolerance(sorted, Double.MAX_VALUE).rangeOf(0D)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedArrayWithTolerance(sorted, Double.MAX_VALUE).rangeOf(Double.NEGATIVE_INFINITY)) .isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedArrayWithTolerance(sorted, Double.MAX_VALUE).rangeOf(Double.POSITIVE_INFINITY)) .isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedArrayWithTolerance(sorted, Double.MAX_VALUE).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedArrayWithTolerance_invalidTolerance() { double[] sorted = new double[] {10, 20, 30, 40}; assertThrows(IllegalArgumentException.class, () -> inSortedArrayWithTolerance(sorted, -1)); assertThrows(IllegalArgumentException.class, () -> inSortedArrayWithTolerance(sorted, -Double.MAX_VALUE)); assertThrows(IllegalArgumentException.class, () -> inSortedArrayWithTolerance(sorted, Double.NEGATIVE_INFINITY)); assertThrows(IllegalArgumentException.class, () -> inSortedArrayWithTolerance(sorted, Double.NaN)); } @Test public void binarySearch_inSortedListWithTolerance_found() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, 0.9).find(20D)).hasValue(1); assertThat(inSortedListWithTolerance(sorted, 1).find(21D)).hasValue(1); assertThat(inSortedListWithTolerance(sorted, 1).find(19D)).hasValue(1); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(20D)).isEqualTo(Range.closed(1, 1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointFor(20D)).isEqualTo(InsertionPoint.at(1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(20D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(20D)).isEqualTo(InsertionPoint.after(1)); } @Test public void binarySearch_inSortedListWithTolerance_notFoundInTheMiddle() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, 1).find(18D)).isEmpty(); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(18D)).isEqualTo(Range.closedOpen(1, 1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointFor(18D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(18D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(18D)).isEqualTo(InsertionPoint.before(1)); } @Test public void binarySearch_inSortedListWithTolerance_notFoundAtTheBeginning() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, 1).find(-1D)).isEmpty(); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(-1D)).isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointFor(Double.MIN_VALUE)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointFor(Double.NEGATIVE_INFINITY)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(-1D)).isEqualTo(InsertionPoint.before(0)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(0D)).isEqualTo(InsertionPoint.before(0)); } @Test public void binarySearch_inSortedListWithTolerance_notFoundAtTheEnd() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, 1).find(42D)).isEmpty(); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(Double.MAX_VALUE)).isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointFor(50D)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(Double.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(Double.MAX_VALUE)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedListWithTolerance(sorted, 100).insertionPointFor(Double.NaN)).isEqualTo(InsertionPoint.after(3)); assertThat(inSortedListWithTolerance(sorted, Double.MAX_VALUE).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); assertThat(inSortedListWithTolerance(sorted, Double.POSITIVE_INFINITY).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedListWithTolerance_withDuplicates() { ImmutableList<Double> sorted = ImmutableList.of(10.1, 20.1, 20.2, 30.1, 40.1, 40.2, 40.3); assertThat(inSortedListWithTolerance(sorted, 1).find(10D)).hasValue(0); assertThat(inSortedListWithTolerance(sorted, 1).find(20D).get()).isIn(ImmutableSet.of(1, 2)); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(20D)).isEqualTo(Range.closed(1, 2)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(20D)).isEqualTo(InsertionPoint.before(1)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(20D)).isEqualTo(InsertionPoint.after(2)); assertThat(inSortedListWithTolerance(sorted, 1).rangeOf(40D)).isEqualTo(Range.closed(4, 6)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointBefore(40D)).isEqualTo(InsertionPoint.before(4)); assertThat(inSortedListWithTolerance(sorted, 1).insertionPointAfter(40D)).isEqualTo(InsertionPoint.after(6)); } @Test public void binarySearch_inSortedListWithTolerance_infinityTolerance() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(0D)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedListWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(Double.NEGATIVE_INFINITY)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedListWithTolerance(sorted, Double.POSITIVE_INFINITY).rangeOf(Double.POSITIVE_INFINITY)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedListWithTolerance(sorted, Double.POSITIVE_INFINITY).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedListWithTolerance_maxTolerance() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThat(inSortedListWithTolerance(sorted, Double.MAX_VALUE).rangeOf(0D)) .isEqualTo(Range.closed(0, 3)); assertThat(inSortedListWithTolerance(sorted, Double.MAX_VALUE).rangeOf(Double.NEGATIVE_INFINITY)) .isEqualTo(Range.closedOpen(0, 0)); assertThat(inSortedListWithTolerance(sorted, Double.MAX_VALUE).rangeOf(Double.POSITIVE_INFINITY)) .isEqualTo(Range.closedOpen(4, 4)); assertThat(inSortedListWithTolerance(sorted, Double.MAX_VALUE).insertionPointFor(Double.NaN)) .isEqualTo(InsertionPoint.after(3)); } @Test public void binarySearch_inSortedListWithTolerance_invalidTolerance() { ImmutableList<Double> sorted = ImmutableList.of(10D, 20D, 30D, 40D); assertThrows(IllegalArgumentException.class, () -> inSortedListWithTolerance(sorted, -1)); assertThrows(IllegalArgumentException.class, () -> inSortedListWithTolerance(sorted, -Double.MAX_VALUE)); assertThrows(IllegalArgumentException.class, () -> inSortedListWithTolerance(sorted, Double.NEGATIVE_INFINITY)); assertThrows(IllegalArgumentException.class, () -> inSortedListWithTolerance(sorted, Double.NaN)); } @Test public void testNulls() throws Exception { new NullPointerTester().testAllPublicStaticMethods(BinarySearch.class); new ClassSanityTester().forAllPublicStaticMethods(BinarySearch.class).testNulls(); } @Test public void binarySearchIntSqrt_smallNumbers() { assertThat(intSqrt().insertionPointFor(4L).floor()).isEqualTo(2); assertThat(intSqrt().insertionPointFor(1L).floor()).isEqualTo(1); assertThat(intSqrt().insertionPointFor(0L).floor()).isEqualTo(0); assertThat(intSqrt().insertionPointFor(5L).floor()).isEqualTo(2); assertThat(intSqrt().insertionPointFor(101L).floor()).isEqualTo(10); assertThat(intSqrt().insertionPointFor(4097L).floor()).isEqualTo(64); } @Test public void binarySearchIntSqrt_largeNumbers() { int[] numbers = { Integer.MAX_VALUE, Integer.MAX_VALUE - 1, Integer.MAX_VALUE - 2, Integer.MAX_VALUE / 2, Integer.MAX_VALUE / 10 }; for (int n : numbers) { long square = ((long) n) * n; assertThat(intSqrt().insertionPointFor(square).floor()).isEqualTo(n); assertThat(intSqrt().insertionPointFor(square + 1).floor()).isEqualTo(n); assertThat(intSqrt().insertionPointFor(square - 1).floor()).isEqualTo(n - 1); assertThat(intSqrt().find(square)).hasValue(n); assertThat(intSqrt().find(square + 1)).isEmpty(); assertThat(intSqrt().find(square - 1)).isEmpty(); } } @Test public void binarySearchDoubleSqrt_smallNumbers( @TestParameter( {"0", "0.1", "0.2", "0.5", "1", "2", "3", "4", "5", "10", "20", "100", "1000", "9999999999"}) double square) { double epsilon = 0.0000000001; InsertionPoint<Double> insertionPoint = squareRoot().insertionPointFor(square); assertThat(insertionPoint.floor()).isWithin(epsilon).of(Math.sqrt(square)); assertThat(insertionPoint.ceiling()).isWithin(epsilon).of(Math.sqrt(square)); } @Test public void binarySearchDoubleCubeRoot_smallNumbers( @TestParameter( {"0", "0.1", "0.2", "0.5", "1", "2", "-3", "4", "5", "10", "-20", "100", "1000", "-9999.99999"}) double cube) { double epsilon = 0.0000000001; InsertionPoint<Double> insertionPoint = cubeRoot().insertionPointFor(cube); assertThat(insertionPoint.floor()).isWithin(epsilon).of(Math.cbrt(cube)); assertThat(insertionPoint.ceiling()).isWithin(epsilon).of(Math.cbrt(cube)); } @Test public void forDoubles_fullRange_smallNumberFound( @TestParameter( {"0", "0.1", "1", "100", "1000", "9999999999", "-1", "-100.345", "-999999.999"}) double secret) { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_fullRange_maxValueFound() { double secret = Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); assertThat(BinarySearch.forDoubles() .rangeOf((low, mid, high) -> Double.compare(secret, mid))) .isEqualTo(Range.closed(secret, secret)); } @Test public void forDoubles_fullRange_maxValueNotFound() { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> 1); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(Double.MAX_VALUE); assertThat(insertionPoint.ceiling()).isEqualTo(Double.POSITIVE_INFINITY); assertThat(BinarySearch.forDoubles().rangeOf(((low, mid, high) -> 1))) .isEqualTo(Range.closedOpen(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)); } @Test public void forDoubles_fullRange_minValueFound() { double secret = -Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); assertThat(BinarySearch.forDoubles() .rangeOf((low, mid, high) -> Double.compare(secret, mid))) .isEqualTo(Range.closed(secret, secret)); } @Test public void forDoubles_fullRange_minValueNotFound() { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> -1); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(Double.NEGATIVE_INFINITY); assertThat(insertionPoint.ceiling()).isEqualTo(-Double.MAX_VALUE); assertThat(BinarySearch.forDoubles().rangeOf(((low, mid, high) -> -1))) .isEqualTo(Range.closedOpen(-Double.MAX_VALUE, -Double.MAX_VALUE)); } @Test public void forDoubles_nonNegativeRange_smallNumberFound( @TestParameter( {"0", "0.1", "1", "100", "1000", "9999999999"}) double secret) { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.atLeast(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); assertThat(BinarySearch.forDoubles(Range.atLeast(0D)) .rangeOf((low, mid, high) -> Double.compare(secret, mid))) .isEqualTo(Range.closed(secret, secret)); } @Test public void forDoubles_positiveRange_smallNumberFound( @TestParameter( {"0.1", "1", "100", "1000", "9999999999"}) double secret) { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.greaterThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_positiveRange_maxValueFound() { double secret = Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.greaterThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_positiveRange_largeNumberFound() { double secret = Double.MAX_VALUE / Integer.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.greaterThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_positiveRange_maxValueNotFound() { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(greaterThan(0D)) .insertionPointFor((low, mid, high) -> 1); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(Double.MAX_VALUE); assertThat(insertionPoint.ceiling()).isEqualTo(Double.POSITIVE_INFINITY); } @Test public void forDoubles_singletonRange_maxValueFound() { double secret = Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.closed(secret, secret)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.exact()).hasValue(secret); } @Test public void forDoubles_singletonRange_maxValueNotFound() { double secret = Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.closed(secret, secret)) .insertionPointFor((low, mid, high) -> -1); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(Double.NEGATIVE_INFINITY); assertThat(insertionPoint.ceiling()).isEqualTo(Double.MAX_VALUE); } @Test public void forDoubles_singletonRange_minValueFound() { double secret = Double.MIN_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.closed(secret, secret)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.exact()).hasValue(secret); } @Test public void forDoubles_singletonRange_minValueNotFound() { double secret = Double.MIN_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(Range.closed(secret, secret)) .insertionPointFor((low, mid, high) -> 1); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(Double.MIN_VALUE); assertThat(insertionPoint.ceiling()).isEqualTo(Double.POSITIVE_INFINITY); } @Test public void forDoubles_emptyRange( @TestParameter({"-1", "-0.5", "0", "0.1", "1", "100"}) double at) { assertThat(BinarySearch.forDoubles(Range.closedOpen(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.before(at)); assertThat(BinarySearch.forDoubles(Range.openClosed(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.after(at)); } @Test public void forDoubles_emptyRange_maxValue() { double at = Double.MAX_VALUE; assertThat(BinarySearch.forDoubles(Range.closedOpen(at, at)) .rangeOf((low, mid, high) -> 0)) .isEqualTo(Range.closedOpen(at, at)); assertThat(BinarySearch.forDoubles(Range.closedOpen(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.before(at)); assertThat(BinarySearch.forDoubles(Range.openClosed(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.after(at)); } @Test public void forDoubles_emptyRange_negativeMaxValue() { double at = -Double.MAX_VALUE; assertThat(BinarySearch.forDoubles(Range.closedOpen(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.before(at)); assertThat(BinarySearch.forDoubles(Range.openClosed(at, at)) .insertionPointFor((low, mid, high) -> 0)).isEqualTo(InsertionPoint.after(at)); } @Test public void forDoubles_emptyRange_infinityDisallowed() { assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(Range.closedOpen(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(Range.closedOpen(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(Range.openClosed(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(Range.openClosed(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY))); } @Test public void forDoubles_fullRange_infinityNotFound() { double secret = Double.POSITIVE_INFINITY; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(Double.MAX_VALUE); assertThat(insertionPoint.ceiling()).isEqualTo(Double.POSITIVE_INFINITY); } @Test public void forDoubles_fullRange_negativeInfinityNotFound() { double secret = Double.NEGATIVE_INFINITY; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles() .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.ceiling()).isEqualTo(-Double.MAX_VALUE); assertThat(insertionPoint.floor()).isEqualTo(Double.NEGATIVE_INFINITY); } @Test public void forDoubles_negativeRange_smallNumberFound( @TestParameter({"-1", "-100.345", "-999999.999"}) double secret) { InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(lessThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_negativeRange_maxValueFound() { double secret = -Double.MIN_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(lessThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isWithin(2 * Double.MIN_NORMAL).of(secret); assertThat(insertionPoint.ceiling()).isWithin(2 * Double.MIN_NORMAL).of(secret); } @Test public void forDoubles_negativeRange_minValueFound() { double secret = -Double.MAX_VALUE; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(lessThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.floor()).isEqualTo(secret); assertThat(insertionPoint.ceiling()).isEqualTo(secret); } @Test public void forDoubles_negativeRange_infinityNotFound() { double secret = Double.POSITIVE_INFINITY; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(lessThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.exact()).isEmpty(); assertThat(insertionPoint.floor()).isEqualTo(-Double.MIN_VALUE); assertThat(insertionPoint.ceiling()).isEqualTo(Double.POSITIVE_INFINITY); } @Test public void forDoubles_negativeRange_negativeInfinityNotFound() { double secret = Double.NEGATIVE_INFINITY; InsertionPoint<Double> insertionPoint = BinarySearch.forDoubles(lessThan(0D)) .insertionPointFor((low, mid, high) -> Double.compare(secret, mid)); assertThat(insertionPoint.ceiling()).isEqualTo(-Double.MAX_VALUE); assertThat(insertionPoint.floor()).isEqualTo(Double.NEGATIVE_INFINITY); } @Test public void forDoubles_infiniteRange_disallowed() { assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(closed(Double.NEGATIVE_INFINITY, 0D))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(closed(Double.NaN, 0D))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(closed(0D, Double.POSITIVE_INFINITY))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(closed(0D, Double.NaN))); assertThrows( IllegalArgumentException.class, () -> BinarySearch.forDoubles(closed(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY))); } @Test public void binarySearchRotated_empty() { int[] sorted = {}; assertThat(inCircularSortedArray(sorted).find(1)).isEmpty(); } @Test public void binarySearchRotated_singleElement() { int[] sorted = {1}; assertThat(inCircularSortedArray(sorted).find(1)).hasValue(0); assertThat(inCircularSortedArray(sorted).find(2)).isEmpty(); } @Test public void binarySearchRotated_twoElements() { int[] sorted = {1, 2}; assertThat(inCircularSortedArray(sorted).find(1)).hasValue(0); assertThat(inCircularSortedArray(sorted).find(2)).hasValue(1); assertThat(inCircularSortedArray(sorted).find(3)).isEmpty(); } @Test public void binarySearchRotated_twoElementsReversed() { int[] sorted = {20, 10}; assertThat(inCircularSortedArray(sorted).find(10)).hasValue(1); assertThat(inCircularSortedArray(sorted).find(20)).hasValue(0); assertThat(inCircularSortedArray(sorted).find(30)).isEmpty(); } @Test public void binarySearchRotated_notRatated() { int[] sorted = {10, 20, 30, 40, 50, 60, 70}; for (int i = 0; i < sorted.length; i++) { assertThat(inCircularSortedArray(sorted).find(sorted[i])).hasValue(i); } assertThat(inCircularSortedArray(sorted).find(0)).isEmpty(); assertThat(inCircularSortedArray(sorted).find(80)).isEmpty(); assertThat(inCircularSortedArray(sorted).find(15)).isEmpty(); } @Test public void binarySearchRotated_ratated() { int[] rotated = {40, 50, 60, 70, 10, 20, 30}; for (int i = 0; i < rotated.length; i++) { assertThat(inCircularSortedArray(rotated).find(rotated[i])).hasValue(i); } assertThat(inCircularSortedArray(rotated).find(0)).isEmpty(); assertThat(inCircularSortedArray(rotated).find(80)).isEmpty(); assertThat(inCircularSortedArray(rotated).find(15)).isEmpty(); } @Test public void guessTheNumberGame( @TestParameter(valuesProvider = LongValues.class) long secret) { AtomicInteger times = new AtomicInteger(); assertThat(BinarySearch.forLongs().find((low, mid, high) -> { times.incrementAndGet(); return Long.compare(secret, mid); })).hasValue(secret); assertThat(times.get()).isAtMost(65); } @Test public void guessTheDoubleNumberGame( @TestParameter(valuesProvider = DoubleValues.class) double secret) { AtomicInteger times = new AtomicInteger(); ImmutableMap.Builder<Double, Integer> builder = ImmutableMap.builder(); assertThat(BinarySearch.forDoubles().find((low, mid, high) -> { builder.put(mid, times.incrementAndGet()); return Double.compare(secret, mid); })).hasValue(secret); assertThat(builder.buildOrThrow().size()).isAtMost(65); assertThat(times.get()).isAtMost(65); } @Test public void guessTheDoubleNumberWithMostlyPositive( @TestParameter({"-0.5", "-0.1", "0", "0.001", "0.1", "1"}) double secret) { AtomicInteger times = new AtomicInteger(); ImmutableMap.Builder<Double, Integer> builder = ImmutableMap.builder(); assertThat(BinarySearch.forDoubles(atLeast(-1.0)).find((low, mid, high) -> { builder.put(mid, times.incrementAndGet()); return Double.compare(secret, mid); })).hasValue(secret); assertThat(builder.buildOrThrow().size()).isAtMost(65); assertThat(times.get()).isAtMost(65); } @Test public void binarySearch_findMinParabola() { InsertionPoint<Integer> point = BinarySearch.forInts() .insertionPointFor((low, mid, high) -> Double.compare(parabola(mid - 1), parabola(mid))); int solution = point.floor(); assertThat(solution).isEqualTo(-2); } private static double parabola(int x) { return Math.pow(x, 2) + 4 * x - 3; } // Demo how binarySearch() can be used to implement more advanced binary search algorithms // such as searching within a rotated array. private static BinarySearch<Integer, Integer> inCircularSortedArray(int[] rotated) { return BinarySearch.forInts(Range.closedOpen(0, rotated.length)) .by(key -> (low, mid, high) -> { int probe = rotated[mid]; if (key < probe) { // target < mid value. // [low] <= probe means we are in the left half of [4, 5, 6, 1, 2, 3]. // If we are in the first ascending half, it's in the right side if key < // rotated[lower]. // If we are in the second ascending half, the right half is useless. Look left. return rotated[low] <= probe && key < rotated[low] ? 1 : -1; } else if (key > probe) { // key > mid value. // probe <= [high] means we are in the right half of [4, 5, 6, 1, 2, 3]. // If we are in the second ascending half, it's in the left side if key > // rotated[high]. // If we are in the first ascending half, the left side is useless. Look right. return probe <= rotated[high] && key > rotated[high] ? -1 : 1; } else { return 0; } }); } private static BinarySearch<Long, Integer> intSqrt() { return BinarySearch.forInts(atLeast(0)) .by(square -> (low, mid, high) -> Long.compare(square, (long) mid * mid)); } private static BinarySearch<Double, Double> squareRoot() { return BinarySearch.forDoubles(atLeast(0D)) .by(square -> (low, mid, high) -> Double.compare(square, mid * mid)); } private static BinarySearch<Double, Double> cubeRoot() { return BinarySearch.forDoubles() .by(cube -> (low, mid, high) -> Double.compare(cube, mid * mid * mid)); } static class NegativeValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.of( Integer.MIN_VALUE, Integer.MIN_VALUE + 1, Integer.MIN_VALUE / 2, Integer.MIN_VALUE / 3, -3, -2, -1); } } static class NegativeLongValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.of( Long.MIN_VALUE, Long.MIN_VALUE + 1, Long.MIN_VALUE / 2, Long.MIN_VALUE / 3, -3L, -2L, -1L); } } static class NonNegativeValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.of( 0, 1, 2, 3, Integer.MAX_VALUE, Integer.MAX_VALUE - 1, Integer.MAX_VALUE - 2, Integer.MAX_VALUE - 3, Integer.MAX_VALUE / 2, Integer.MAX_VALUE / 3); } } static class NonNegativeLongValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.of( 0L, 1L, 2L, 3L, Long.MAX_VALUE, Long.MAX_VALUE - 1, Long.MAX_VALUE - 2, Long.MAX_VALUE - 3, Long.MAX_VALUE / 2, Long.MAX_VALUE / 3); } } static class IntValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.builder() .addAll(new NegativeValues().provideValues()) .addAll(new NonNegativeValues().provideValues()) .build(); } } static class LongValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.builder() .addAll(new NegativeLongValues().provideValues()) .addAll(new NonNegativeLongValues().provideValues()) .build(); } } static class DoubleValues implements TestParameter.TestParameterValuesProvider { @Override public List<?> provideValues() { return ImmutableList.of( -Long.MAX_VALUE, -Long.MAX_VALUE / 2, -Long.MAX_VALUE / 3, -3D, -2.5D, -1D, 0D, 0.5, 0.123456789, 1D, 2D, 3D, Double.MAX_VALUE, Double.MAX_VALUE / 2, Double.MAX_VALUE / 3); } } }
test invisible double number
mug-guava/src/test/java/com/google/mu/util/BinarySearchTest.java
test invisible double number
Java
apache-2.0
08b6cf240ab4e7414688d70cc308b2e150d67a89
0
anchela/sling,dulvac/sling,labertasch/sling,SylvesterAbreu/sling,dulvac/sling,wimsymons/sling,gutsy/sling,JEBailey/sling,mikibrv/sling,ieb/sling,sdmcraft/sling,mikibrv/sling,wimsymons/sling,trekawek/sling,JEBailey/sling,nleite/sling,Nimco/sling,awadheshv/sling,mikibrv/sling,mmanski/sling,tmaret/sling,tteofili/sling,Sivaramvt/sling,nleite/sling,Nimco/sling,klcodanr/sling,Nimco/sling,tteofili/sling,nleite/sling,gutsy/sling,ffromm/sling,awadheshv/sling,tyge68/sling,Nimco/sling,nleite/sling,ieb/sling,gutsy/sling,ieb/sling,roele/sling,codders/k2-sling-fork,mikibrv/sling,tyge68/sling,JEBailey/sling,plutext/sling,Sivaramvt/sling,dulvac/sling,tyge68/sling,cleliameneghin/sling,vladbailescu/sling,awadheshv/sling,mcdan/sling,klcodanr/sling,ieb/sling,klcodanr/sling,anchela/sling,mmanski/sling,labertasch/sling,anchela/sling,ffromm/sling,awadheshv/sling,awadheshv/sling,labertasch/sling,anchela/sling,mmanski/sling,vladbailescu/sling,plutext/sling,headwirecom/sling,dulvac/sling,SylvesterAbreu/sling,headwirecom/sling,sdmcraft/sling,nleite/sling,tteofili/sling,trekawek/sling,vladbailescu/sling,plutext/sling,plutext/sling,sdmcraft/sling,headwirecom/sling,klcodanr/sling,wimsymons/sling,mcdan/sling,klcodanr/sling,ist-dresden/sling,vladbailescu/sling,ist-dresden/sling,mmanski/sling,mikibrv/sling,tteofili/sling,mcdan/sling,Sivaramvt/sling,plutext/sling,JEBailey/sling,ffromm/sling,trekawek/sling,cleliameneghin/sling,gutsy/sling,JEBailey/sling,dulvac/sling,ieb/sling,wimsymons/sling,sdmcraft/sling,mcdan/sling,mcdan/sling,wimsymons/sling,tteofili/sling,ffromm/sling,trekawek/sling,cleliameneghin/sling,headwirecom/sling,tmaret/sling,tyge68/sling,gutsy/sling,ffromm/sling,tmaret/sling,tyge68/sling,anchela/sling,Sivaramvt/sling,Sivaramvt/sling,roele/sling,ist-dresden/sling,tyge68/sling,Sivaramvt/sling,tmaret/sling,gutsy/sling,SylvesterAbreu/sling,cleliameneghin/sling,dulvac/sling,roele/sling,roele/sling,ieb/sling,mmanski/sling,mcdan/sling,codders/k2-sling-fork,trekawek/sling,klcodanr/sling,nleite/sling,ffromm/sling,sdmcraft/sling,ist-dresden/sling,SylvesterAbreu/sling,Nimco/sling,headwirecom/sling,awadheshv/sling,SylvesterAbreu/sling,vladbailescu/sling,labertasch/sling,codders/k2-sling-fork,wimsymons/sling,roele/sling,sdmcraft/sling,mikibrv/sling,SylvesterAbreu/sling,trekawek/sling,tmaret/sling,labertasch/sling,mmanski/sling,ist-dresden/sling,Nimco/sling,cleliameneghin/sling,plutext/sling,tteofili/sling
/* * 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.sling.jcr.base; import java.util.Dictionary; import javax.jcr.Credentials; import javax.jcr.LoginException; import javax.jcr.NoSuchWorkspaceException; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.SimpleCredentials; import javax.jcr.Workspace; import org.apache.jackrabbit.api.JackrabbitWorkspace; import org.apache.sling.jcr.api.SlingRepository; import org.apache.sling.jcr.base.internal.SessionPool; import org.apache.sling.jcr.base.internal.SessionPoolFactory; import org.apache.sling.jcr.base.internal.SessionPoolManager; import org.apache.sling.jcr.base.internal.loader.Loader; import org.apache.sling.jcr.base.util.RepositoryAccessor; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.ServiceRegistration; import org.osgi.framework.SynchronousBundleListener; import org.osgi.service.component.ComponentContext; import org.osgi.service.log.LogService; /** * The <code>AbstractSlingRepository</code> is an abstract implementation of * the {@link SlingRepository} interface which provides core support for session * pooling. Implementations of the <code>SlingRepository</code> interface may * wish to extend this class to benefit from a default implementation. * <p> * Extensions of this class will have to declare the following * <code>scr.property</code> tags to have them declared automatically in the * respective component and metatype definitions by the maven-sling-plugin: * * @scr.component metatype="no" */ public abstract class AbstractSlingRepository implements SlingRepository, SynchronousBundleListener, Runnable { /** @scr.property value="" */ public static final String PROPERTY_DEFAULT_WORKSPACE = "defaultWorkspace"; /** @scr.property valueRef="DEFAULT_ANONYMOUS_USER" */ public static final String PROPERTY_ANONYMOUS_USER = "anonymous.name"; /** @scr.property valueRef="DEFAULT_ANONYMOUS_PASS" */ public static final String PROPERTY_ANONYMOUS_PASS = "anonymous.password"; /** @scr.property valueRef="DEFAULT_ADMIN_USER" */ public static final String PROPERTY_ADMIN_USER = "admin.name"; /** @scr.property valueRef="DEFAULT_ADMIN_PASS" */ public static final String PROPERTY_ADMIN_PASS = "admin.password"; /** @scr.property valueRef="DEFAULT_POLL_ACTIVE" */ public static final String PROPERTY_POLL_ACTIVE = "poll.active"; /** @scr.property valueRef="DEFAULT_POLL_INACTIVE" */ public static final String PROPERTY_POLL_INACTIVE = "poll.inactive"; /** * The name of the configuration parameter containing the maximum number of * seconds to wait for the number of currently active sessions to drop be * low the upper limit before giving up (value is "pool.maxActiveWait"). * * @scr.property value="1" type="Integer" */ public static final String PROPERTY_MAX_ACTIVE_SESSIONS_WAIT = "pool.maxActiveWait"; /** * The name of the configuration parameter containing the upper limit of the * simultaneously active sessions (value is "pool.maxActive"). * * @scr.property value="-1" type="Integer" */ public static final String PROPERTY_MAX_ACTIVE_SESSIONS = "pool.maxActive"; /** * The name of the configuration parameter containing the upper limit of the * currently idle sessions to keep in the pool (value is "pool.maxIdle"). * * @scr.property value="10" type="Integer" */ public static final String PROPERTY_MAX_IDLE_SESSIONS = "pool.maxIdle"; public static final String DEFAULT_ANONYMOUS_USER = "anonymous"; public static final String DEFAULT_ANONYMOUS_PASS = "anonymous"; public static final String DEFAULT_ADMIN_USER = "admin"; public static final String DEFAULT_ADMIN_PASS = "admin"; /** * The default value for the number of seconds to wait between two * consecutive checks while the repository is active (value is 10). */ public static final int DEFAULT_POLL_ACTIVE = 10; /** * The default value for the number of seconds to wait between two * consecutive checks while the repository is not active (value is 10). */ public static final int DEFAULT_POLL_INACTIVE = 10; /** The minimum number of seconds allowed for any of the two poll times */ public static final int MIN_POLL = 2; /** @scr.reference bind="bindLog" unbind="unbindLog" */ private LogService log; private ComponentContext componentContext; private Repository repository; private ServiceRegistration repositoryService; private String defaultWorkspace; private String anonUser; private char[] anonPass; private String adminUser; private char[] adminPass; private SessionPoolManager poolManager; private Loader loader; // the poll interval used while the repository is not active private long pollTimeInActive; // the poll interval used while the repository is active private long pollTimeActive; // whether the repository checker task should be active. this field // is managed by the startRepositoryPinger and stopRepositoryPinger methods private boolean running; // the background thread constantly checking the repository private Thread repositoryPinger; protected AbstractSlingRepository() { } /** * Returns the default workspace, which may be <code>null</code> meaning * to use the repository provided default workspace. Declared final to make * sure the SLING-256 rule is enforced. */ public final String getDefaultWorkspace() { return defaultWorkspace; } private void setDefaultWorkspace(String defaultWorkspace) { // normalize the default workspace name: trim leading and trailing // blanks and set to null in case the trimmed name is empty if (defaultWorkspace != null) { defaultWorkspace = defaultWorkspace.trim(); if (defaultWorkspace.length() == 0) { defaultWorkspace = null; } } log(LogService.LOG_DEBUG, "setDefaultWorkspace: Setting the default workspace to " + defaultWorkspace); this.defaultWorkspace = defaultWorkspace; } /** * Logs in as an anonymous user. This implementation simply returns the * result of calling {@link #login(Credentials, String)} */ public Session login() throws LoginException, RepositoryException { return this.login(null, null); } public Session loginAdministrative(String workspace) throws RepositoryException { SimpleCredentials sc = new SimpleCredentials(this.adminUser, this.adminPass); return this.login(sc, workspace); } public Session login(Credentials credentials) throws LoginException, RepositoryException { return this.login(credentials, null); } public Session login(String workspace) throws LoginException, NoSuchWorkspaceException, RepositoryException { return this.login(null, workspace); } public Session login(Credentials credentials, String workspace) throws LoginException, NoSuchWorkspaceException, RepositoryException { // if already stopped, don't retrieve a session if (this.componentContext == null || this.getRepository() == null) { throw new RepositoryException("Sling Repository not ready"); } if (credentials == null) { credentials = new SimpleCredentials(this.anonUser, this.anonPass); } // check the workspace if (workspace == null) { workspace = this.getDefaultWorkspace(); } try { log(LogService.LOG_DEBUG, "login: Logging in to workspace '" + workspace + "'"); Session session = getPoolManager().login(credentials, workspace); // if the defualt workspace is null, acquire a session from the pool // and use the workspace used as the new default workspace if (workspace == null) { String defaultWorkspace = session.getWorkspace().getName(); log(LogService.LOG_DEBUG, "login: Using " + defaultWorkspace + " as the default workspace instead of 'null'"); setDefaultWorkspace(defaultWorkspace); } return session; } catch (NoSuchWorkspaceException nswe) { // if the desired workspace is the default workspace, try to create // (but not if using the repository-supplied default workspace) if (workspace != null && workspace.equals(this.getDefaultWorkspace()) && this.createWorkspace(workspace)) { return this.getPoolManager().login(credentials, workspace); } // otherwise (any workspace) or if workspace creation fails // just forward the original exception throw nswe; } } /* * (non-Javadoc) * * @see javax.jcr.Repository#getDescriptor(java.lang.String) */ public String getDescriptor(String name) { Repository repo = getRepository(); if (repo != null) { return repo.getDescriptor(name); } log(LogService.LOG_ERROR, "getDescriptor: Repository not available"); return null; } /* * (non-Javadoc) * * @see javax.jcr.Repository#getDescriptorKeys() */ public String[] getDescriptorKeys() { Repository repo = getRepository(); if (repo != null) { return repo.getDescriptorKeys(); } log(LogService.LOG_ERROR, "getDescriptorKeys: Repository not available"); return new String[0]; } // ---------- Session Pool support ----------------------------------------- protected final SessionPoolManager getPoolManager() { if (this.poolManager == null) { this.poolManager = new SessionPoolManager(this.getRepository(), this.loader, this.getSessionPoolFactory()); } return this.poolManager; } /** * @return */ protected SessionPoolFactory getSessionPoolFactory() { @SuppressWarnings("unchecked") Dictionary<String, Object> properties = this.componentContext.getProperties(); final int maxActiveSessions = this.getIntProperty(properties, PROPERTY_MAX_ACTIVE_SESSIONS); final int maxIdleSessions = this.getIntProperty(properties, PROPERTY_MAX_IDLE_SESSIONS); final int maxActiveSessionsWait = this.getIntProperty(properties, PROPERTY_MAX_ACTIVE_SESSIONS_WAIT); return new SessionPoolFactory() { public SessionPool createPool(final SessionPoolManager mgr, final SimpleCredentials credentials) { // create and configure the new pool final SessionPool pool = createSessionPool(mgr, credentials); pool.setMaxActiveSessions(maxActiveSessions); pool.setMaxActiveSessionsWait(maxActiveSessionsWait); pool.setMaxIdleSessions(maxIdleSessions); return pool; } }; } protected SessionPool createSessionPool(final SessionPoolManager mgr, final SimpleCredentials credentials) { final SessionPool pool = new SessionPool(mgr, credentials); return pool; } // ---------- logging ------------------------------------------------------ protected void log(int level, String message) { this.log(level, message, null); } protected void log(int level, String message, Throwable t) { LogService log = this.log; if (log != null) { if (componentContext != null) { log.log(componentContext.getServiceReference(), level, message, t); } else { log.log(level, message, t); } } } // ---------- Repository Access ------------------------------------------- /** * Returns a new instance of the {@link RepositoryAccessor} class to access * a repository over RMI or through JNDI. * <p> * Extensions of this method may return an extension of the * {@link RepositoryAccessor} class if the provide extended functionality. */ protected RepositoryAccessor getRepositoryAccessor() { return new RepositoryAccessor(); } /** * Acquires the repository by calling the * {@link org.apache.sling.jcr.base.util.RepositoryAccessor#getRepositoryFromURL(String)} * with the value of the * {@link org.apache.sling.jcr.base.util.RepositoryAccessor#REPOSITORY_URL_OVERRIDE_PROPERTY} * framework or configuration property. If the property exists and a * repository can be accessed using this property, that repository is * returned. Otherwise <code>null</code> is returned. * <p> * Extensions of this class may overwrite this method with implementation * specific acquisition semantics and may call this base class method or not * as the implementation sees fit. * <p> * This method does not throw any <code>Throwable</code> but instead just * returns <code>null</code> if not repository is available. Any problems * trying to acquire the repository must be caught and logged as * appropriate. * * @return The acquired JCR <code>Repository</code> or <code>null</code> * if not repository can be acquired. */ protected Repository acquireRepository() { // if the environment provides a repository override URL, other settings // are ignored String overrideUrl = (String) componentContext.getProperties().get( RepositoryAccessor.REPOSITORY_URL_OVERRIDE_PROPERTY); if (overrideUrl == null) { overrideUrl = componentContext.getBundleContext().getProperty( RepositoryAccessor.REPOSITORY_URL_OVERRIDE_PROPERTY); } if (overrideUrl != null && overrideUrl.length() > 0) { log(LogService.LOG_INFO, "acquireRepository: Will not use embedded repository due to property " + RepositoryAccessor.REPOSITORY_URL_OVERRIDE_PROPERTY + "=" + overrideUrl + ", acquiring repository using that URL"); return getRepositoryAccessor().getRepositoryFromURL(overrideUrl); } log(LogService.LOG_DEBUG, "acquireRepository: No existing repository to access"); return null; } /** * This method is called after a repository has been acquired by * {@link #acquireRepository()} but before the repository is registered as a * service. * <p> * Implementations may overwrite this method but MUST call this base class * implementation first. * * @param repository The JCR <code>Repository</code> to setup. */ protected void setupRepository(Repository repository) { BundleContext bundleContext = componentContext.getBundleContext(); this.loader = new Loader(this, bundleContext.getBundles()); } /** * Registers this component as an OSGi service with type * <code>javax.jcr.Repository</code> and * <code>org.apache.sling.jcr.api.SlingRepository</code> using the * component properties as service registration properties. * <p> * This method may be overwritten to register the component with different * types. * * @return The OSGi <code>ServiceRegistration</code> object representing * the registered service. */ protected ServiceRegistration registerService() { @SuppressWarnings("unchecked") Dictionary<String, Object> props = componentContext.getProperties(); String[] interfaces = new String[] { SlingRepository.class.getName(), Repository.class.getName() }; return componentContext.getBundleContext().registerService(interfaces, this, props); } /** * Returns the repository underlying this instance or <code>null</code> if * no repository is currently being available. */ protected Repository getRepository() { return repository; } /** * Checks that the given <code>repository</code> is still available. This * implementation tries to get the <code>Repository.SPEC_NAME_DESC</code> * descriptor from the repository and returns <code>true</code> if the * returned value is not <code>null</code>. * <p> * Extensions of this class may overwrite this method to implement different * access checks. The contract of this method must be obeyed, though in a * sense, the <code>true</code> must only be returned if * <code>repository</code> is actually usable. * * @param repository The JCR <code>Repository</code> to check for * availability. * @return <code>true</code> if <code>repository</code> is not * <code>null</code> and accessible. */ protected boolean pingRepository(Repository repository) { if (repository != null) { try { return repository.getDescriptor(Repository.SPEC_NAME_DESC) != null; } catch (Throwable t) { log(LogService.LOG_DEBUG, "pingRepository: Repository " + repository + " does not seem to be available any more", t); } } // fall back to unavailable return false; } /** Ping our current repository and check that admin login (required by Sling) works. */ protected boolean pingAndCheck() { if(repository == null) { throw new IllegalStateException("Repository is null"); } boolean result = false; if(pingRepository(repository)) { try { final Session s = loginAdministrative(getDefaultWorkspace()); s.logout(); result = true; } catch(RepositoryException re) { log.log(LogService.LOG_INFO, "pingAndCheck; loginAdministrative failed", re); } } return result; } /** * Unregisters the service represented by the * <code>serviceRegistration</code>. * <p> * This method may be overwritten by extensions of this class as long as it * is made sure, the given service registration is unregistered. */ protected void unregisterService(ServiceRegistration serviceRegistration) { serviceRegistration.unregister(); } /** * Performs any cleanups before the repository is actually disposed off by * the {@link #disposeRepository(Repository)} method. * <p> * This method is meant for cleanup tasks before the repository is actually * disposed off. Extensions of this class may overwrite but must call this * base class implementation. * * @param repository */ protected void tearDown(Repository repository) { if (this.poolManager != null) { this.poolManager.dispose(); this.poolManager = null; } if (this.loader != null) { this.loader.dispose(); this.loader = null; } } /** * Disposes off the given <code>repository</code>. This base class * implementation does nothing. Extensions should overwrite if any special * disposal operation is required. * * @param repository */ protected void disposeRepository(Repository repository) { // nothing to do here ... } // ---------- SynchronousBundleListener ------------------------------------ /** * Loads and unloads any components provided by the bundle whose state * changed. If the bundle has been started, the components are loaded. If * the bundle is about to stop, the components are unloaded. * * @param event The <code>BundleEvent</code> representing the bundle state * change. */ public void bundleChanged(BundleEvent event) { // Take care: This is synchronous - take care to not block the system !! Loader theLoader = this.loader; if (theLoader != null) { switch (event.getType()) { case BundleEvent.INSTALLED: // register types when the bundle gets installed theLoader.registerBundle(event.getBundle()); break; case BundleEvent.UNINSTALLED: theLoader.unregisterBundle(event.getBundle()); break; case BundleEvent.UPDATED: theLoader.updateBundle(event.getBundle()); } } } // --------- SCR integration ----------------------------------------------- protected ComponentContext getComponentContext() { return this.componentContext; } /** * This method must be called if overwritten by implementations !! * * @throws nothing, but allow derived classes to throw any Exception */ protected void activate(ComponentContext componentContext) throws Exception { this.componentContext = componentContext; @SuppressWarnings("unchecked") Dictionary<String, Object> properties = componentContext.getProperties(); setDefaultWorkspace(this.getProperty(properties, PROPERTY_DEFAULT_WORKSPACE, null)); this.anonUser = this.getProperty(properties, PROPERTY_ANONYMOUS_USER, DEFAULT_ANONYMOUS_USER); this.anonPass = this.getProperty(properties, PROPERTY_ANONYMOUS_PASS, DEFAULT_ANONYMOUS_PASS).toCharArray(); this.adminUser = this.getProperty(properties, PROPERTY_ADMIN_USER, DEFAULT_ADMIN_USER); this.adminPass = this.getProperty(properties, PROPERTY_ADMIN_PASS, DEFAULT_ADMIN_PASS).toCharArray(); setPollTimeActive(getIntProperty(properties, PROPERTY_POLL_ACTIVE)); setPollTimeInActive(getIntProperty(properties, PROPERTY_POLL_INACTIVE)); componentContext.getBundleContext().addBundleListener(this); // immediately try to start the repository while activating // this component instance try { startRepository(); } catch (Throwable t) { log(LogService.LOG_WARNING, "activate: Unexpected problem starting repository", t); } // launch the background repository checker now startRepositoryPinger(); } /** * This method must be called if overwritten by implementations !! * * @param componentContext */ protected void deactivate(ComponentContext componentContext) { componentContext.getBundleContext().removeBundleListener(this); // stop the background thread stopRepositoryPinger(); // ensure the repository is really disposed off if (repository != null || repositoryService != null) { log(LogService.LOG_INFO, "deactivate: Repository still running, forcing shutdown"); try { stopRepository(); } catch (Throwable t) { log(LogService.LOG_WARNING, "deactivate: Unexpected problem stopping repository", t); } } this.componentContext = null; } protected void bindLog(LogService log) { this.log = log; } protected void unbindLog(LogService log) { if (this.log == log) { log = null; } } // ---------- internal ----------------------------------------------------- private String getProperty(Dictionary<String, Object> properties, String name, String defaultValue) { Object prop = properties.get(name); return (prop instanceof String) ? (String) prop : defaultValue; } private int getIntProperty(Dictionary<String, Object> properties, String name) { Object prop = properties.get(name); if (prop instanceof Number) { return ((Number) prop).intValue(); } else if (prop != null) { try { return Integer.decode(String.valueOf(prop)).intValue(); } catch (NumberFormatException nfe) { // don't really care } } return -1; } private boolean createWorkspace(String workspace) { this.log(LogService.LOG_INFO, "createWorkspace: Requested workspace " + workspace + " does not exist, trying to create"); Session tmpSession = null; try { SimpleCredentials sc = new SimpleCredentials(this.adminUser, this.adminPass); tmpSession = this.getRepository().login(sc); Workspace defaultWs = tmpSession.getWorkspace(); if (defaultWs instanceof JackrabbitWorkspace) { ((JackrabbitWorkspace) defaultWs).createWorkspace(workspace); return true; } // not Jackrabbit this.log(LogService.LOG_ERROR, "createWorkspace: Cannot create requested workspace " + workspace + ": Jackrabbit is required"); } catch (Throwable t) { this.log(LogService.LOG_ERROR, "createWorkspace: Cannot create requested workspace " + workspace, t); } finally { if (tmpSession != null) { tmpSession.logout(); } } // fall back to failure return false; } // ---------- Background operation checking repository availability -------- private void setPollTimeActive(int seconds) { if (seconds < MIN_POLL) { seconds = DEFAULT_POLL_ACTIVE; } pollTimeActive = 1000L * seconds; } private void setPollTimeInActive(int seconds) { if (seconds < MIN_POLL) { seconds = DEFAULT_POLL_INACTIVE; } pollTimeInActive = 1000L * seconds; } private void startRepositoryPinger() { if (repositoryPinger == null) { // make sure the ping will be running running = true; // create and start the thread repositoryPinger = new Thread(this, "Repository Pinger"); repositoryPinger.start(); } } private void stopRepositoryPinger() { // make sure the thread is terminating running = false; // nothing to do if the thread is not running at all Thread rpThread = repositoryPinger; if (rpThread == null) { return; } // clear the repositoryPinger thread field repositoryPinger = null; // notify the thread for it to be able to shut down synchronized (rpThread) { rpThread.notifyAll(); } // wait at most 10 seconds for the thread to terminate try { rpThread.join(10000L); } catch (InterruptedException ie) { // don't care here } // consider it an error if the thread is still running !! if (rpThread.isAlive()) { log(LogService.LOG_ERROR, "stopRepositoryPinger: Timed waiting for thread " + rpThread + " to terminate"); } } private boolean startRepository() { try { log(LogService.LOG_DEBUG, "startRepository: calling acquireRepository()"); Repository newRepo = acquireRepository(); if (newRepo != null) { // ensure we really have the repository log(LogService.LOG_DEBUG, "startRepository: got a Repository, calling pingRepository()"); if (pingRepository(newRepo)) { repository = newRepo; if(!pingAndCheck()) { repository = null; log(LogService.LOG_DEBUG, "pingRepository() successful but pingAndCheck() fails, will try again"); return false; } else { log(LogService.LOG_DEBUG, "startRepository: pingRepository() and pingAndCheck() successful, calling setupRepository()"); setupRepository(newRepo); log(LogService.LOG_DEBUG, "startRepository: calling registerService()"); repositoryService = registerService(); log(LogService.LOG_DEBUG, "registerService() successful, registration=" + repositoryService); return true; } } // otherwise let go of the repository and fail startup log(LogService.LOG_DEBUG, "startRepository: pingRepository() failed, calling disposeRepository()"); disposeRepository(repository); } } catch (Throwable t) { // consider an uncaught problem an error log( LogService.LOG_ERROR, "startRepository: Uncaught Throwable trying to access Repository, calling stopRepository()", t); // repository might be partially started, stop anything left stopRepository(); } return false; } private void stopRepository() { if (repositoryService != null) { try { log(LogService.LOG_DEBUG, "Unregistering SlingRepository service, registration=" + repositoryService); unregisterService(repositoryService); } catch (Throwable t) { log( LogService.LOG_INFO, "stopRepository: Uncaught problem unregistering the repository service", t); } repositoryService = null; } if (repository != null) { Repository oldRepo = repository; repository = null; try { tearDown(oldRepo); } catch (Throwable t) { log( LogService.LOG_INFO, "stopRepository: Uncaught problem tearing down the repository", t); } try { disposeRepository(oldRepo); } catch (Throwable t) { log( LogService.LOG_INFO, "stopRepository: Uncaught problem disposing the repository", t); } } } public void run() { // start polling with min value to be faster at system startup // we'll increase the polling time after each try long pollTime = MIN_POLL; final long pollTimeIncrement = 1; Object waitLock = repositoryPinger; try { while (running) { // wait first before starting to check synchronized (waitLock) { try { log(LogService.LOG_DEBUG, "Waiting " + pollTime + " seconds before checking repository"); waitLock.wait(pollTime * 1000L); } catch (InterruptedException ie) { // don't care, go ahead } } // only apply any checks if we are running after waiting if (running) { Repository repo = repository; if (repo == null) { if (startRepository()) { pollTime = pollTimeActive; } } else if (!pingAndCheck()) { log(LogService.LOG_INFO, "run: Repository not accessible, unregistering service"); stopRepository(); pollTime = Math.min(pollTime + pollTimeIncrement, pollTimeInActive); } else { log(LogService.LOG_DEBUG, "run: Repository available, checking again in " + pollTime + "ms"); } } } } finally { // whatever goes on, make sure the repository is disposed off // at the end of the thread.... stopRepository(); } } }
jcr/base/src/main/java/org/apache/sling/jcr/base/AbstractSlingRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.jcr.base; import java.util.Dictionary; import javax.jcr.Credentials; import javax.jcr.LoginException; import javax.jcr.NoSuchWorkspaceException; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.SimpleCredentials; import javax.jcr.Workspace; import org.apache.jackrabbit.api.JackrabbitWorkspace; import org.apache.sling.jcr.api.SlingRepository; import org.apache.sling.jcr.base.internal.SessionPool; import org.apache.sling.jcr.base.internal.SessionPoolFactory; import org.apache.sling.jcr.base.internal.SessionPoolManager; import org.apache.sling.jcr.base.internal.loader.Loader; import org.apache.sling.jcr.base.util.RepositoryAccessor; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.ServiceRegistration; import org.osgi.framework.SynchronousBundleListener; import org.osgi.service.component.ComponentContext; import org.osgi.service.log.LogService; /** * The <code>AbstractSlingRepository</code> is an abstract implementation of * the {@link SlingRepository} interface which provides core support for session * pooling. Implementations of the <code>SlingRepository</code> interface may * wish to extend this class to benefit from a default implementation. * <p> * Extensions of this class will have to declare the following * <code>scr.property</code> tags to have them declared automatically in the * respective component and metatype definitions by the maven-sling-plugin: * * @scr.component metatype="no" */ public abstract class AbstractSlingRepository implements SlingRepository, SynchronousBundleListener, Runnable { /** @scr.property value="" */ public static final String PROPERTY_DEFAULT_WORKSPACE = "defaultWorkspace"; /** @scr.property valueRef="DEFAULT_ANONYMOUS_USER" */ public static final String PROPERTY_ANONYMOUS_USER = "anonymous.name"; /** @scr.property valueRef="DEFAULT_ANONYMOUS_PASS" */ public static final String PROPERTY_ANONYMOUS_PASS = "anonymous.password"; /** @scr.property valueRef="DEFAULT_ADMIN_USER" */ public static final String PROPERTY_ADMIN_USER = "admin.name"; /** @scr.property valueRef="DEFAULT_ADMIN_PASS" */ public static final String PROPERTY_ADMIN_PASS = "admin.password"; /** @scr.property valueRef="DEFAULT_POLL_ACTIVE" */ public static final String PROPERTY_POLL_ACTIVE = "poll.active"; /** @scr.property valueRef="DEFAULT_POLL_INACTIVE" */ public static final String PROPERTY_POLL_INACTIVE = "poll.inactive"; /** * The name of the configuration parameter containing the maximum number of * seconds to wait for the number of currently active sessions to drop be * low the upper limit before giving up (value is "pool.maxActiveWait"). * * @scr.property value="1" type="Integer" */ public static final String PROPERTY_MAX_ACTIVE_SESSIONS_WAIT = "pool.maxActiveWait"; /** * The name of the configuration parameter containing the upper limit of the * simultaneously active sessions (value is "pool.maxActive"). * * @scr.property value="-1" type="Integer" */ public static final String PROPERTY_MAX_ACTIVE_SESSIONS = "pool.maxActive"; /** * The name of the configuration parameter containing the upper limit of the * currently idle sessions to keep in the pool (value is "pool.maxIdle"). * * @scr.property value="10" type="Integer" */ public static final String PROPERTY_MAX_IDLE_SESSIONS = "pool.maxIdle"; public static final String DEFAULT_ANONYMOUS_USER = "anonymous"; public static final String DEFAULT_ANONYMOUS_PASS = "anonymous"; public static final String DEFAULT_ADMIN_USER = "admin"; public static final String DEFAULT_ADMIN_PASS = "admin"; /** * The default value for the number of seconds to wait between two * consecutive checks while the repository is active (value is 10). */ public static final int DEFAULT_POLL_ACTIVE = 10; /** * The default value for the number of seconds to wait between two * consecutive checks while the repository is not active (value is 10). */ public static final int DEFAULT_POLL_INACTIVE = 10; /** The minimum number of seconds allowed for any of the two poll times */ public static final int MIN_POLL = 2; /** @scr.reference bind="bindLog" unbind="unbindLog" */ private LogService log; private ComponentContext componentContext; private Repository repository; private ServiceRegistration repositoryService; private String defaultWorkspace; private String anonUser; private char[] anonPass; private String adminUser; private char[] adminPass; private SessionPoolManager poolManager; private Loader loader; // the poll interval used while the repository is not active private long pollTimeInActive; // the poll interval used while the repository is active private long pollTimeActive; // whether the repository checker task should be active. this field // is managed by the startRepositoryPinger and stopRepositoryPinger methods private boolean running; // the background thread constantly checking the repository private Thread repositoryPinger; protected AbstractSlingRepository() { } /** * Returns the default workspace, which may be <code>null</code> meaning * to use the repository provided default workspace. Declared final to make * sure the SLING-256 rule is enforced. */ public final String getDefaultWorkspace() { if (defaultWorkspace == null || defaultWorkspace.trim().length() == 0) { // SLING-256 return null; } return this.defaultWorkspace; } /** * Logs in as an anonymous user. This implementation simply returns the * result of calling {@link #login(Credentials, String)} */ public Session login() throws LoginException, RepositoryException { return this.login(null, null); } public Session loginAdministrative(String workspace) throws RepositoryException { SimpleCredentials sc = new SimpleCredentials(this.adminUser, this.adminPass); return this.login(sc, workspace); } public Session login(Credentials credentials) throws LoginException, RepositoryException { return this.login(credentials, null); } public Session login(String workspace) throws LoginException, NoSuchWorkspaceException, RepositoryException { return this.login(null, workspace); } public Session login(Credentials credentials, String workspace) throws LoginException, NoSuchWorkspaceException, RepositoryException { // if already stopped, don't retrieve a session if (this.componentContext == null || this.getRepository() == null) { throw new RepositoryException("Sling Repository not ready"); } if (credentials == null) { credentials = new SimpleCredentials(this.anonUser, this.anonPass); } // check the workspace if (workspace == null) { workspace = this.getDefaultWorkspace(); } try { log(LogService.LOG_DEBUG, "login: Logging in to workspace '" + workspace + "'"); return this.getPoolManager().login(credentials, workspace); } catch (NoSuchWorkspaceException nswe) { // if the desired workspace is the default workspace, try to create // (but not if using the repository-supplied default workspace) if (workspace != null && workspace.equals(this.getDefaultWorkspace()) && this.createWorkspace(workspace)) { return this.getPoolManager().login(credentials, workspace); } // otherwise (any workspace) or if workspace creation fails // just forward the original exception throw nswe; } } /* * (non-Javadoc) * * @see javax.jcr.Repository#getDescriptor(java.lang.String) */ public String getDescriptor(String name) { Repository repo = getRepository(); if (repo != null) { return repo.getDescriptor(name); } log(LogService.LOG_ERROR, "getDescriptor: Repository not available"); return null; } /* * (non-Javadoc) * * @see javax.jcr.Repository#getDescriptorKeys() */ public String[] getDescriptorKeys() { Repository repo = getRepository(); if (repo != null) { return repo.getDescriptorKeys(); } log(LogService.LOG_ERROR, "getDescriptorKeys: Repository not available"); return new String[0]; } // ---------- Session Pool support ----------------------------------------- protected final SessionPoolManager getPoolManager() { if (this.poolManager == null) { this.poolManager = new SessionPoolManager(this.getRepository(), this.loader, this.getSessionPoolFactory()); } return this.poolManager; } /** * @return */ protected SessionPoolFactory getSessionPoolFactory() { @SuppressWarnings("unchecked") Dictionary<String, Object> properties = this.componentContext.getProperties(); final int maxActiveSessions = this.getIntProperty(properties, PROPERTY_MAX_ACTIVE_SESSIONS); final int maxIdleSessions = this.getIntProperty(properties, PROPERTY_MAX_IDLE_SESSIONS); final int maxActiveSessionsWait = this.getIntProperty(properties, PROPERTY_MAX_ACTIVE_SESSIONS_WAIT); return new SessionPoolFactory() { public SessionPool createPool(final SessionPoolManager mgr, final SimpleCredentials credentials) { // create and configure the new pool final SessionPool pool = createSessionPool(mgr, credentials); pool.setMaxActiveSessions(maxActiveSessions); pool.setMaxActiveSessionsWait(maxActiveSessionsWait); pool.setMaxIdleSessions(maxIdleSessions); return pool; } }; } protected SessionPool createSessionPool(final SessionPoolManager mgr, final SimpleCredentials credentials) { final SessionPool pool = new SessionPool(mgr, credentials); return pool; } // ---------- logging ------------------------------------------------------ protected void log(int level, String message) { this.log(level, message, null); } protected void log(int level, String message, Throwable t) { LogService log = this.log; if (log != null) { if (componentContext != null) { log.log(componentContext.getServiceReference(), level, message, t); } else { log.log(level, message, t); } } } // ---------- Repository Access ------------------------------------------- /** * Returns a new instance of the {@link RepositoryAccessor} class to access * a repository over RMI or through JNDI. * <p> * Extensions of this method may return an extension of the * {@link RepositoryAccessor} class if the provide extended functionality. */ protected RepositoryAccessor getRepositoryAccessor() { return new RepositoryAccessor(); } /** * Acquires the repository by calling the * {@link org.apache.sling.jcr.base.util.RepositoryAccessor#getRepositoryFromURL(String)} * with the value of the * {@link org.apache.sling.jcr.base.util.RepositoryAccessor#REPOSITORY_URL_OVERRIDE_PROPERTY} * framework or configuration property. If the property exists and a * repository can be accessed using this property, that repository is * returned. Otherwise <code>null</code> is returned. * <p> * Extensions of this class may overwrite this method with implementation * specific acquisition semantics and may call this base class method or not * as the implementation sees fit. * <p> * This method does not throw any <code>Throwable</code> but instead just * returns <code>null</code> if not repository is available. Any problems * trying to acquire the repository must be caught and logged as * appropriate. * * @return The acquired JCR <code>Repository</code> or <code>null</code> * if not repository can be acquired. */ protected Repository acquireRepository() { // if the environment provides a repository override URL, other settings // are ignored String overrideUrl = (String) componentContext.getProperties().get( RepositoryAccessor.REPOSITORY_URL_OVERRIDE_PROPERTY); if (overrideUrl == null) { overrideUrl = componentContext.getBundleContext().getProperty( RepositoryAccessor.REPOSITORY_URL_OVERRIDE_PROPERTY); } if (overrideUrl != null && overrideUrl.length() > 0) { log(LogService.LOG_INFO, "acquireRepository: Will not use embedded repository due to property " + RepositoryAccessor.REPOSITORY_URL_OVERRIDE_PROPERTY + "=" + overrideUrl + ", acquiring repository using that URL"); return getRepositoryAccessor().getRepositoryFromURL(overrideUrl); } log(LogService.LOG_DEBUG, "acquireRepository: No existing repository to access"); return null; } /** * This method is called after a repository has been acquired by * {@link #acquireRepository()} but before the repository is registered as a * service. * <p> * Implementations may overwrite this method but MUST call this base class * implementation first. * * @param repository The JCR <code>Repository</code> to setup. */ protected void setupRepository(Repository repository) { BundleContext bundleContext = componentContext.getBundleContext(); this.loader = new Loader(this, bundleContext.getBundles()); } /** * Registers this component as an OSGi service with type * <code>javax.jcr.Repository</code> and * <code>org.apache.sling.jcr.api.SlingRepository</code> using the * component properties as service registration properties. * <p> * This method may be overwritten to register the component with different * types. * * @return The OSGi <code>ServiceRegistration</code> object representing * the registered service. */ protected ServiceRegistration registerService() { @SuppressWarnings("unchecked") Dictionary<String, Object> props = componentContext.getProperties(); String[] interfaces = new String[] { SlingRepository.class.getName(), Repository.class.getName() }; return componentContext.getBundleContext().registerService(interfaces, this, props); } /** * Returns the repository underlying this instance or <code>null</code> if * no repository is currently being available. */ protected Repository getRepository() { return repository; } /** * Checks that the given <code>repository</code> is still available. This * implementation tries to get the <code>Repository.SPEC_NAME_DESC</code> * descriptor from the repository and returns <code>true</code> if the * returned value is not <code>null</code>. * <p> * Extensions of this class may overwrite this method to implement different * access checks. The contract of this method must be obeyed, though in a * sense, the <code>true</code> must only be returned if * <code>repository</code> is actually usable. * * @param repository The JCR <code>Repository</code> to check for * availability. * @return <code>true</code> if <code>repository</code> is not * <code>null</code> and accessible. */ protected boolean pingRepository(Repository repository) { if (repository != null) { try { return repository.getDescriptor(Repository.SPEC_NAME_DESC) != null; } catch (Throwable t) { log(LogService.LOG_DEBUG, "pingRepository: Repository " + repository + " does not seem to be available any more", t); } } // fall back to unavailable return false; } /** Ping our current repository and check that admin login (required by Sling) works. */ protected boolean pingAndCheck() { if(repository == null) { throw new IllegalStateException("Repository is null"); } boolean result = false; if(pingRepository(repository)) { try { final Session s = loginAdministrative(getDefaultWorkspace()); s.logout(); result = true; } catch(RepositoryException re) { log.log(LogService.LOG_INFO, "pingAndCheck; loginAdministrative failed", re); } } return result; } /** * Unregisters the service represented by the * <code>serviceRegistration</code>. * <p> * This method may be overwritten by extensions of this class as long as it * is made sure, the given service registration is unregistered. */ protected void unregisterService(ServiceRegistration serviceRegistration) { serviceRegistration.unregister(); } /** * Performs any cleanups before the repository is actually disposed off by * the {@link #disposeRepository(Repository)} method. * <p> * This method is meant for cleanup tasks before the repository is actually * disposed off. Extensions of this class may overwrite but must call this * base class implementation. * * @param repository */ protected void tearDown(Repository repository) { if (this.poolManager != null) { this.poolManager.dispose(); this.poolManager = null; } if (this.loader != null) { this.loader.dispose(); this.loader = null; } } /** * Disposes off the given <code>repository</code>. This base class * implementation does nothing. Extensions should overwrite if any special * disposal operation is required. * * @param repository */ protected void disposeRepository(Repository repository) { // nothing to do here ... } // ---------- SynchronousBundleListener ------------------------------------ /** * Loads and unloads any components provided by the bundle whose state * changed. If the bundle has been started, the components are loaded. If * the bundle is about to stop, the components are unloaded. * * @param event The <code>BundleEvent</code> representing the bundle state * change. */ public void bundleChanged(BundleEvent event) { // Take care: This is synchronous - take care to not block the system !! Loader theLoader = this.loader; if (theLoader != null) { switch (event.getType()) { case BundleEvent.INSTALLED: // register types when the bundle gets installed theLoader.registerBundle(event.getBundle()); break; case BundleEvent.UNINSTALLED: theLoader.unregisterBundle(event.getBundle()); break; case BundleEvent.UPDATED: theLoader.updateBundle(event.getBundle()); } } } // --------- SCR integration ----------------------------------------------- protected ComponentContext getComponentContext() { return this.componentContext; } /** * This method must be called if overwritten by implementations !! * * @throws nothing, but allow derived classes to throw any Exception */ protected void activate(ComponentContext componentContext) throws Exception { this.componentContext = componentContext; @SuppressWarnings("unchecked") Dictionary<String, Object> properties = componentContext.getProperties(); // ensure the default workspace is not null and not empty this.defaultWorkspace = this.getProperty(properties, PROPERTY_DEFAULT_WORKSPACE, null); if (this.defaultWorkspace != null && this.defaultWorkspace.length() == 0) { this.defaultWorkspace = null; } this.anonUser = this.getProperty(properties, PROPERTY_ANONYMOUS_USER, DEFAULT_ANONYMOUS_USER); this.anonPass = this.getProperty(properties, PROPERTY_ANONYMOUS_PASS, DEFAULT_ANONYMOUS_PASS).toCharArray(); this.adminUser = this.getProperty(properties, PROPERTY_ADMIN_USER, DEFAULT_ADMIN_USER); this.adminPass = this.getProperty(properties, PROPERTY_ADMIN_PASS, DEFAULT_ADMIN_PASS).toCharArray(); setPollTimeActive(getIntProperty(properties, PROPERTY_POLL_ACTIVE)); setPollTimeInActive(getIntProperty(properties, PROPERTY_POLL_INACTIVE)); componentContext.getBundleContext().addBundleListener(this); // immediately try to start the repository while activating // this component instance try { startRepository(); } catch (Throwable t) { log(LogService.LOG_WARNING, "activate: Unexpected problem starting repository", t); } // launch the background repository checker now startRepositoryPinger(); } /** * This method must be called if overwritten by implementations !! * * @param componentContext */ protected void deactivate(ComponentContext componentContext) { componentContext.getBundleContext().removeBundleListener(this); // stop the background thread stopRepositoryPinger(); // ensure the repository is really disposed off if (repository != null || repositoryService != null) { log(LogService.LOG_INFO, "deactivate: Repository still running, forcing shutdown"); try { stopRepository(); } catch (Throwable t) { log(LogService.LOG_WARNING, "deactivate: Unexpected problem stopping repository", t); } } this.componentContext = null; } protected void bindLog(LogService log) { this.log = log; } protected void unbindLog(LogService log) { if (this.log == log) { log = null; } } // ---------- internal ----------------------------------------------------- private String getProperty(Dictionary<String, Object> properties, String name, String defaultValue) { Object prop = properties.get(name); return (prop instanceof String) ? (String) prop : defaultValue; } private int getIntProperty(Dictionary<String, Object> properties, String name) { Object prop = properties.get(name); if (prop instanceof Number) { return ((Number) prop).intValue(); } else if (prop != null) { try { return Integer.decode(String.valueOf(prop)).intValue(); } catch (NumberFormatException nfe) { // don't really care } } return -1; } private boolean createWorkspace(String workspace) { this.log(LogService.LOG_INFO, "createWorkspace: Requested workspace " + workspace + " does not exist, trying to create"); Session tmpSession = null; try { SimpleCredentials sc = new SimpleCredentials(this.adminUser, this.adminPass); tmpSession = this.getRepository().login(sc); Workspace defaultWs = tmpSession.getWorkspace(); if (defaultWs instanceof JackrabbitWorkspace) { ((JackrabbitWorkspace) defaultWs).createWorkspace(workspace); return true; } // not Jackrabbit this.log(LogService.LOG_ERROR, "createWorkspace: Cannot create requested workspace " + workspace + ": Jackrabbit is required"); } catch (Throwable t) { this.log(LogService.LOG_ERROR, "createWorkspace: Cannot create requested workspace " + workspace, t); } finally { if (tmpSession != null) { tmpSession.logout(); } } // fall back to failure return false; } // ---------- Background operation checking repository availability -------- private void setPollTimeActive(int seconds) { if (seconds < MIN_POLL) { seconds = DEFAULT_POLL_ACTIVE; } pollTimeActive = 1000L * seconds; } private void setPollTimeInActive(int seconds) { if (seconds < MIN_POLL) { seconds = DEFAULT_POLL_INACTIVE; } pollTimeInActive = 1000L * seconds; } private void startRepositoryPinger() { if (repositoryPinger == null) { // make sure the ping will be running running = true; // create and start the thread repositoryPinger = new Thread(this, "Repository Pinger"); repositoryPinger.start(); } } private void stopRepositoryPinger() { // make sure the thread is terminating running = false; // nothing to do if the thread is not running at all Thread rpThread = repositoryPinger; if (rpThread == null) { return; } // clear the repositoryPinger thread field repositoryPinger = null; // notify the thread for it to be able to shut down synchronized (rpThread) { rpThread.notifyAll(); } // wait at most 10 seconds for the thread to terminate try { rpThread.join(10000L); } catch (InterruptedException ie) { // don't care here } // consider it an error if the thread is still running !! if (rpThread.isAlive()) { log(LogService.LOG_ERROR, "stopRepositoryPinger: Timed waiting for thread " + rpThread + " to terminate"); } } private boolean startRepository() { try { log(LogService.LOG_DEBUG, "startRepository: calling acquireRepository()"); Repository newRepo = acquireRepository(); if (newRepo != null) { // ensure we really have the repository log(LogService.LOG_DEBUG, "startRepository: got a Repository, calling pingRepository()"); if (pingRepository(newRepo)) { repository = newRepo; if(!pingAndCheck()) { repository = null; log(LogService.LOG_DEBUG, "pingRepository() successful but pingAndCheck() fails, will try again"); return false; } else { log(LogService.LOG_DEBUG, "startRepository: pingRepository() and pingAndCheck() successful, calling setupRepository()"); setupRepository(newRepo); log(LogService.LOG_DEBUG, "startRepository: calling registerService()"); repositoryService = registerService(); log(LogService.LOG_DEBUG, "registerService() successful, registration=" + repositoryService); return true; } } // otherwise let go of the repository and fail startup log(LogService.LOG_DEBUG, "startRepository: pingRepository() failed, calling disposeRepository()"); disposeRepository(repository); } } catch (Throwable t) { // consider an uncaught problem an error log( LogService.LOG_ERROR, "startRepository: Uncaught Throwable trying to access Repository, calling stopRepository()", t); // repository might be partially started, stop anything left stopRepository(); } return false; } private void stopRepository() { if (repositoryService != null) { try { log(LogService.LOG_DEBUG, "Unregistering SlingRepository service, registration=" + repositoryService); unregisterService(repositoryService); } catch (Throwable t) { log( LogService.LOG_INFO, "stopRepository: Uncaught problem unregistering the repository service", t); } repositoryService = null; } if (repository != null) { Repository oldRepo = repository; repository = null; try { tearDown(oldRepo); } catch (Throwable t) { log( LogService.LOG_INFO, "stopRepository: Uncaught problem tearing down the repository", t); } try { disposeRepository(oldRepo); } catch (Throwable t) { log( LogService.LOG_INFO, "stopRepository: Uncaught problem disposing the repository", t); } } } public void run() { // start polling with min value to be faster at system startup // we'll increase the polling time after each try long pollTime = MIN_POLL; final long pollTimeIncrement = 1; Object waitLock = repositoryPinger; try { while (running) { // wait first before starting to check synchronized (waitLock) { try { log(LogService.LOG_DEBUG, "Waiting " + pollTime + " seconds before checking repository"); waitLock.wait(pollTime * 1000L); } catch (InterruptedException ie) { // don't care, go ahead } } // only apply any checks if we are running after waiting if (running) { Repository repo = repository; if (repo == null) { if (startRepository()) { pollTime = pollTimeActive; } } else if (!pingAndCheck()) { log(LogService.LOG_INFO, "run: Repository not accessible, unregistering service"); stopRepository(); pollTime = Math.min(pollTime + pollTimeIncrement, pollTimeInActive); } else { log(LogService.LOG_DEBUG, "run: Repository available, checking again in " + pollTime + "ms"); } } } } finally { // whatever goes on, make sure the repository is disposed off // at the end of the thread.... stopRepository(); } } }
SLING-488 Reset default workspace to actual default workspace used by the Repository.login method if the default workspace is not configured in Sling. git-svn-id: c3eb811ccca381e673aa62a65336ec26649ed58c@661655 13f79535-47bb-0310-9956-ffa450edef68
jcr/base/src/main/java/org/apache/sling/jcr/base/AbstractSlingRepository.java
SLING-488 Reset default workspace to actual default workspace used by the Repository.login method if the default workspace is not configured in Sling.
Java
apache-2.0
0c9f1b7d7602322fc73eae3b67f0f7be9224d8a3
0
caskdata/cdap,caskdata/cdap,mpouttuclarke/cdap,hsaputra/cdap,anthcp/cdap,hsaputra/cdap,hsaputra/cdap,chtyim/cdap,chtyim/cdap,anthcp/cdap,caskdata/cdap,mpouttuclarke/cdap,caskdata/cdap,caskdata/cdap,anthcp/cdap,hsaputra/cdap,chtyim/cdap,chtyim/cdap,hsaputra/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,anthcp/cdap,chtyim/cdap,mpouttuclarke/cdap,anthcp/cdap,caskdata/cdap,chtyim/cdap
package com.continuuity.test.app; import com.continuuity.api.app.Application; import com.continuuity.api.data.dataset.table.Get; import com.continuuity.api.data.dataset.table.Put; import com.continuuity.api.data.dataset.table.Table; import com.continuuity.api.dataset.DatasetProperties; import com.continuuity.app.program.RunRecord; import com.continuuity.test.ApplicationManager; import com.continuuity.test.DataSetManager; import com.continuuity.test.FlowManager; import com.continuuity.test.MapReduceManager; import com.continuuity.test.ProcedureClient; import com.continuuity.test.ProcedureManager; import com.continuuity.test.ReactorTestBase; import com.continuuity.test.RuntimeMetrics; import com.continuuity.test.RuntimeStats; import com.continuuity.test.ServiceManager; import com.continuuity.test.SlowTests; import com.continuuity.test.StreamWriter; import com.continuuity.test.WorkflowManager; import com.continuuity.test.XSlowTests; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.primitives.Longs; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.Type; import java.sql.Connection; import java.sql.ResultSet; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * */ @Category(SlowTests.class) public class TestFrameworkTest extends ReactorTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestFrameworkTest.class); @After public void cleanup() throws Exception { // Sleep a second before clear. There is a race between removal of RuntimeInfo // in the AbstractProgramRuntimeService class and the clear() method, which loops all RuntimeInfo. // The reason for the race is because removal is done through callback. TimeUnit.SECONDS.sleep(1); clear(); } @Test public void testFlowRuntimeArguments() throws Exception { ApplicationManager applicationManager = deployApplication(FilterApp.class); try { Map<String, String> args = Maps.newHashMap(); args.put("threshold", "10"); applicationManager.startFlow("FilterFlow", args); StreamWriter input = applicationManager.getStreamWriter("input"); input.send("1"); input.send("11"); ProcedureManager queryManager = applicationManager.startProcedure("Count"); ProcedureClient client = queryManager.getClient(); Gson gson = new Gson(); Assert.assertEquals("1", gson.fromJson(client.query("result", ImmutableMap.of("type", "highpass")), String.class)); } finally { applicationManager.stopAll(); TimeUnit.SECONDS.sleep(1); } } @Category(XSlowTests.class) @Test public void testDeployWorkflowApp() throws InterruptedException { ApplicationManager applicationManager = deployApplication(AppWithSchedule.class); WorkflowManager wfmanager = applicationManager.startWorkflow("SampleWorkflow", null); List<String> schedules = wfmanager.getSchedules(); Assert.assertEquals(1, schedules.size()); String scheduleId = schedules.get(0); Assert.assertNotNull(scheduleId); Assert.assertFalse(scheduleId.isEmpty()); TimeUnit.SECONDS.sleep(5); List<RunRecord> history = wfmanager.getHistory(); int workflowRuns = history.size(); Assert.assertTrue(workflowRuns >= 1); String status = wfmanager.getSchedule(scheduleId).status(); Assert.assertEquals("SCHEDULED", status); wfmanager.getSchedule(scheduleId).suspend(); Assert.assertEquals("SUSPENDED", wfmanager.getSchedule(scheduleId).status()); history = wfmanager.getHistory(); workflowRuns = history.size(); //Sleep for some time and verify there are no more scheduled jobs after the suspend. TimeUnit.SECONDS.sleep(10); int workflowRunsAfterSuspend = wfmanager.getHistory().size(); Assert.assertEquals(workflowRuns, workflowRunsAfterSuspend); wfmanager.getSchedule(scheduleId).resume(); TimeUnit.SECONDS.sleep(3); int workflowRunsAfterResume = wfmanager.getHistory().size(); //Verify there is atleast one run after the pause Assert.assertTrue(workflowRunsAfterResume > workflowRunsAfterSuspend + 1); //check scheduled state Assert.assertEquals("SCHEDULED", wfmanager.getSchedule(scheduleId).status()); //check status of non-existent schedule Assert.assertEquals("NOT_FOUND", wfmanager.getSchedule("doesnt exist").status()); //suspend the schedule wfmanager.getSchedule(scheduleId).suspend(); Assert.assertEquals("SUSPENDED", wfmanager.getSchedule(scheduleId).status()); TimeUnit.SECONDS.sleep(2); applicationManager.stopAll(); } @Category(XSlowTests.class) @Test(timeout = 240000) public void testMultiInput() throws InterruptedException, IOException, TimeoutException { ApplicationManager applicationManager = deployApplication(JoinMultiStreamApp.class); try { applicationManager.startFlow("JoinMultiFlow"); StreamWriter s1 = applicationManager.getStreamWriter("s1"); StreamWriter s2 = applicationManager.getStreamWriter("s2"); StreamWriter s3 = applicationManager.getStreamWriter("s3"); s1.send("testing 1"); s2.send("testing 2"); s3.send("testing 3"); RuntimeMetrics terminalMetrics = RuntimeStats.getFlowletMetrics("JoinMulti", "JoinMultiFlow", "Terminal"); terminalMetrics.waitForProcessed(3, 5, TimeUnit.SECONDS); TimeUnit.SECONDS.sleep(1); ProcedureManager queryManager = applicationManager.startProcedure("Query"); Gson gson = new Gson(); ProcedureClient client = queryManager.getClient(); Assert.assertEquals("testing 1", gson.fromJson(client.query("get", ImmutableMap.of("key", "input1")), String.class)); Assert.assertEquals("testing 2", gson.fromJson(client.query("get", ImmutableMap.of("key", "input2")), String.class)); Assert.assertEquals("testing 3", gson.fromJson(client.query("get", ImmutableMap.of("key", "input3")), String.class)); } finally { applicationManager.stopAll(); } } @Category(XSlowTests.class) @Test(timeout = 360000) public void testApp() throws InterruptedException, IOException, TimeoutException { testApp(WordCountApp2.class, false, "text2"); } @Category(XSlowTests.class) @Test(timeout = 360000) public void testAppWithDatasetV2() throws InterruptedException, IOException, TimeoutException { testApp(WordCountAppV2.class, true, "text"); } @Test public void testAppwithServices() throws Exception { ApplicationManager applicationManager = deployApplication(AppWithServices.class); LOG.info("Deployed."); ServiceManager serviceManager = applicationManager.startService("NoOpService"); Assert.assertTrue(serviceManager.isRunning()); LOG.info("Service Started"); serviceManager.stop(); Assert.assertFalse(serviceManager.isRunning()); LOG.info("Service Stopped"); // we can verify metrics, by adding getServiceMetrics in RuntimeStats and then disabling the REACTOR scope test in // TestMetricsCollectionService } // todo: passing stream name as a workaround for not cleaning up streams during reset() private void testApp(Class<?> app, boolean datasetV2, String streamName) throws IOException, TimeoutException, InterruptedException { ApplicationManager applicationManager = deployApplication(app); try { applicationManager.startFlow("WordCountFlow"); // Send some inputs to streams StreamWriter streamWriter = applicationManager.getStreamWriter(streamName); for (int i = 0; i < 100; i++) { streamWriter.send(ImmutableMap.of("title", "title " + i), "testing message " + i); } // Check the flowlet metrics RuntimeMetrics flowletMetrics = RuntimeStats.getFlowletMetrics("WordCountApp", "WordCountFlow", "CountByField"); flowletMetrics.waitForProcessed(500, 10, TimeUnit.SECONDS); Assert.assertEquals(0L, flowletMetrics.getException()); // Query the result ProcedureManager procedureManager = applicationManager.startProcedure("WordFrequency"); ProcedureClient procedureClient = procedureManager.getClient(); // Verify the query result Type resultType = new TypeToken<Map<String, Long>>() { }.getType(); Gson gson = new Gson(); Map<String, Long> result = gson.fromJson(procedureClient.query("wordfreq", ImmutableMap.of("word", streamName + ":testing")), resultType); Assert.assertEquals(100L, result.get(streamName + ":testing").longValue()); // check the metrics RuntimeMetrics procedureMetrics = RuntimeStats.getProcedureMetrics("WordCountApp", "WordFrequency"); procedureMetrics.waitForProcessed(1, 5, TimeUnit.SECONDS); Assert.assertEquals(0L, procedureMetrics.getException()); // Run mapreduce job MapReduceManager mrManager = applicationManager.startMapReduce("countTotal"); mrManager.waitForFinish(180L, TimeUnit.SECONDS); long totalCount = Long.valueOf(procedureClient.query("total", Collections.<String, String>emptyMap())); // every event has 5 tokens Assert.assertEquals(5 * 100L, totalCount); // Run mapreduce from stream mrManager = applicationManager.startMapReduce("countFromStream"); mrManager.waitForFinish(120L, TimeUnit.SECONDS); totalCount = Long.valueOf(procedureClient.query("stream_total", Collections.<String, String>emptyMap())); // The stream MR only consume the body, not the header. Assert.assertEquals(3 * 100L, totalCount); // Verify by looking into dataset // todo: ugly workaround, refactor when datasets v1 gone if (!datasetV2) { DataSetManager<MyKeyValueTable> mydatasetManager = applicationManager.getDataSet("mydataset"); Assert.assertEquals(100L, Longs.fromByteArray(mydatasetManager.get().read("title:title".getBytes(Charsets.UTF_8)))); } else { DataSetManager<MyKeyValueTableDefinition.KeyValueTable> mydatasetManager = applicationManager.getDataSet("mydataset"); Assert.assertEquals(100L, Long.valueOf(mydatasetManager.get().get("title:title")).longValue()); } } finally { applicationManager.stopAll(); } } @Category(SlowTests.class) @Test public void testGenerator() throws InterruptedException, IOException, TimeoutException { ApplicationManager applicationManager = deployApplication(GenSinkApp2.class); try { applicationManager.startFlow("GenSinkFlow"); // Check the flowlet metrics RuntimeMetrics genMetrics = RuntimeStats.getFlowletMetrics("GenSinkApp", "GenSinkFlow", "GenFlowlet"); RuntimeMetrics sinkMetrics = RuntimeStats.getFlowletMetrics("GenSinkApp", "GenSinkFlow", "SinkFlowlet"); RuntimeMetrics batchSinkMetrics = RuntimeStats.getFlowletMetrics("GenSinkApp", "GenSinkFlow", "BatchSinkFlowlet"); // Generator generators 99 events + 99 batched events sinkMetrics.waitForProcessed(198, 5, TimeUnit.SECONDS); Assert.assertEquals(0L, sinkMetrics.getException()); // Batch sink only get the 99 batch events batchSinkMetrics.waitForProcessed(99, 5, TimeUnit.SECONDS); Assert.assertEquals(0L, batchSinkMetrics.getException()); Assert.assertEquals(1L, genMetrics.getException()); } finally { applicationManager.stopAll(); } } @Test public void testAppRedeployKeepsData() { ApplicationManager appManager = deployApplication(AppWithTable.class); DataSetManager<Table> myTableManager = appManager.getDataSet("my_table"); myTableManager.get().put(new Put("key1", "column1", "value1")); myTableManager.flush(); // Changes should be visible to other instances of datasets DataSetManager<Table> myTableManager2 = appManager.getDataSet("my_table"); Assert.assertEquals("value1", myTableManager2.get().get(new Get("key1", "column1")).getString("column1")); // Even after redeploy of an app: changes should be visible to other instances of datasets appManager = deployApplication(AppWithTable.class); DataSetManager<Table> myTableManager3 = appManager.getDataSet("my_table"); Assert.assertEquals("value1", myTableManager3.get().get(new Get("key1", "column1")).getString("column1")); // Calling commit again (to test we can call it multiple times) myTableManager.get().put(new Put("key1", "column1", "value2")); myTableManager.flush(); Assert.assertEquals("value1", myTableManager3.get().get(new Get("key1", "column1")).getString("column1")); } @Test (timeout = 30000L) public void testInitDataSetAccess() throws TimeoutException, InterruptedException { ApplicationManager appManager = deployApplication(DataSetInitApp.class); FlowManager flowManager = appManager.startFlow("DataSetFlow"); RuntimeMetrics flowletMetrics = RuntimeStats.getFlowletMetrics("DataSetInitApp", "DataSetFlow", "Consumer"); flowletMetrics.waitForProcessed(1, 5, TimeUnit.SECONDS); flowManager.stop(); DataSetManager<Table> dataSetManager = appManager.getDataSet("conf"); Table confTable = dataSetManager.get(); Assert.assertEquals("generator", confTable.get(new Get("key", "column")).getString("column")); dataSetManager.flush(); } @Test(timeout = 60000L) public void testAppWithAutoDeployDatasetModule() throws Exception { testAppWithDataset(AppsWithDataset.AppWithAutoDeploy.class, "MyProcedure"); } @Test(timeout = 60000L) public void testAppWithAutoDeployDataset() throws Exception { deployDatasetModule("my-kv", AppsWithDataset.KeyValueTableDefinition.Module.class); // we should be fine if module is already there. Deploy of module should not happen testAppWithDataset(AppsWithDataset.AppWithAutoDeploy.class, "MyProcedure"); } @Test(timeout = 60000L) public void testAppWithAutoCreateDataset() throws Exception { deployDatasetModule("my-kv", AppsWithDataset.KeyValueTableDefinition.Module.class); testAppWithDataset(AppsWithDataset.AppWithAutoCreate.class, "MyProcedure"); } @Test(timeout = 60000L) public void testAppWithExistingDataset() throws Exception { deployDatasetModule("my-kv", AppsWithDataset.KeyValueTableDefinition.Module.class); addDatasetInstance("myKeyValueTable", "myTable", DatasetProperties.EMPTY).create(); testAppWithDataset(AppsWithDataset.AppWithExisting.class, "MyProcedure"); } @Test(timeout = 60000L) public void testAppWithExistingDatasetInjectedByAnnotation() throws Exception { deployDatasetModule("my-kv", AppsWithDataset.KeyValueTableDefinition.Module.class); addDatasetInstance("myKeyValueTable", "myTable", DatasetProperties.EMPTY).create(); testAppWithDataset(AppsWithDataset.AppUsesAnnotation.class, "MyProcedureWithUseDataSetAnnotation"); } @Test(timeout = 60000L) public void testAppWithAutoDeployDatasetType() throws Exception { testAppWithDataset(AppsWithDataset.AppWithAutoDeployType.class, "MyProcedure"); } @Test(timeout = 60000L) public void testAppWithAutoDeployDatasetTypeShortcut() throws Exception { testAppWithDataset(AppsWithDataset.AppWithAutoDeployTypeShortcut.class, "MyProcedure"); } private void testAppWithDataset(Class<? extends Application> app, String procedureName) throws Exception { ApplicationManager applicationManager = deployApplication(app); try { // Query the result ProcedureManager procedureManager = applicationManager.startProcedure(procedureName); ProcedureClient procedureClient = procedureManager.getClient(); procedureClient.query("set", ImmutableMap.of("key", "key1", "value", "value1")); String response = procedureClient.query("get", ImmutableMap.of("key", "key1")); Assert.assertEquals("value1", new Gson().fromJson(response, String.class)); } finally { TimeUnit.SECONDS.sleep(2); applicationManager.stopAll(); } } @Test(timeout = 60000L) public void testSQLQuery() throws Exception { deployDatasetModule("my-kv", AppsWithDataset.KeyValueTableDefinition.Module.class); ApplicationManager appManager = deployApplication(AppsWithDataset.AppWithAutoCreate.class); DataSetManager<AppsWithDataset.KeyValueTableDefinition.KeyValueTable> myTableManager = appManager.getDataSet("myTable"); AppsWithDataset.KeyValueTableDefinition.KeyValueTable kvTable = myTableManager.get(); kvTable.put("a", "1"); kvTable.put("b", "2"); kvTable.put("c", "1"); myTableManager.flush(); Connection connection = getQueryClient(); try { // list the tables and make sure the table is there ResultSet results = connection.prepareStatement("show tables").executeQuery(); Assert.assertTrue(results.next()); Assert.assertTrue("continuuity_user_myTable".equalsIgnoreCase(results.getString(1))); // run a query over the dataset results = connection.prepareStatement("select first from continuuity_user_mytable where second = '1'") .executeQuery(); Assert.assertTrue(results.next()); Assert.assertEquals("a", results.getString(1)); Assert.assertTrue(results.next()); Assert.assertEquals("c", results.getString(1)); Assert.assertFalse(results.next()); } finally { connection.close(); appManager.stopAll(); } } }
continuuity-test/src/test/java/com/continuuity/test/app/TestFrameworkTest.java
package com.continuuity.test.app; import com.continuuity.api.app.Application; import com.continuuity.api.data.dataset.table.Get; import com.continuuity.api.data.dataset.table.Put; import com.continuuity.api.data.dataset.table.Table; import com.continuuity.api.dataset.DatasetProperties; import com.continuuity.app.ProgramStatus; import com.continuuity.app.program.RunRecord; import com.continuuity.test.ApplicationManager; import com.continuuity.test.DataSetManager; import com.continuuity.test.FlowManager; import com.continuuity.test.MapReduceManager; import com.continuuity.test.ProcedureClient; import com.continuuity.test.ProcedureManager; import com.continuuity.test.ReactorTestBase; import com.continuuity.test.RuntimeMetrics; import com.continuuity.test.RuntimeStats; import com.continuuity.test.ServiceManager; import com.continuuity.test.SlowTests; import com.continuuity.test.StreamWriter; import com.continuuity.test.WorkflowManager; import com.continuuity.test.XSlowTests; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.primitives.Longs; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.Type; import java.sql.Connection; import java.sql.ResultSet; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * */ @Category(SlowTests.class) public class TestFrameworkTest extends ReactorTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestFrameworkTest.class); @After public void cleanup() throws Exception { // Sleep a second before clear. There is a race between removal of RuntimeInfo // in the AbstractProgramRuntimeService class and the clear() method, which loops all RuntimeInfo. // The reason for the race is because removal is done through callback. TimeUnit.SECONDS.sleep(1); clear(); } @Test public void testFlowRuntimeArguments() throws Exception { ApplicationManager applicationManager = deployApplication(FilterApp.class); try { Map<String, String> args = Maps.newHashMap(); args.put("threshold", "10"); applicationManager.startFlow("FilterFlow", args); StreamWriter input = applicationManager.getStreamWriter("input"); input.send("1"); input.send("11"); ProcedureManager queryManager = applicationManager.startProcedure("Count"); ProcedureClient client = queryManager.getClient(); Gson gson = new Gson(); Assert.assertEquals("1", gson.fromJson(client.query("result", ImmutableMap.of("type", "highpass")), String.class)); } finally { applicationManager.stopAll(); TimeUnit.SECONDS.sleep(1); } } @Category(XSlowTests.class) @Test public void testDeployWorkflowApp() throws InterruptedException { ApplicationManager applicationManager = deployApplication(AppWithSchedule.class); WorkflowManager wfmanager = applicationManager.startWorkflow("SampleWorkflow", null); List<String> schedules = wfmanager.getSchedules(); Assert.assertEquals(1, schedules.size()); String scheduleId = schedules.get(0); Assert.assertNotNull(scheduleId); Assert.assertFalse(scheduleId.isEmpty()); TimeUnit.SECONDS.sleep(5); List<RunRecord> history = wfmanager.getHistory(); int workflowRuns = history.size(); Assert.assertTrue(workflowRuns >= 1); String status = wfmanager.getSchedule(scheduleId).status(); Assert.assertEquals("SCHEDULED", status); wfmanager.getSchedule(scheduleId).suspend(); Assert.assertEquals("SUSPENDED", wfmanager.getSchedule(scheduleId).status()); history = wfmanager.getHistory(); workflowRuns = history.size(); //Sleep for some time and verify there are no more scheduled jobs after the suspend. TimeUnit.SECONDS.sleep(10); int workflowRunsAfterSuspend = wfmanager.getHistory().size(); Assert.assertEquals(workflowRuns, workflowRunsAfterSuspend); wfmanager.getSchedule(scheduleId).resume(); TimeUnit.SECONDS.sleep(3); int workflowRunsAfterResume = wfmanager.getHistory().size(); //Verify there is atleast one run after the pause Assert.assertTrue(workflowRunsAfterResume > workflowRunsAfterSuspend + 1); //check scheduled state Assert.assertEquals("SCHEDULED", wfmanager.getSchedule(scheduleId).status()); //check status of non-existent schedule Assert.assertEquals("NOT_FOUND", wfmanager.getSchedule("doesnt exist").status()); //suspend the schedule wfmanager.getSchedule(scheduleId).suspend(); Assert.assertEquals("SUSPENDED", wfmanager.getSchedule(scheduleId).status()); TimeUnit.SECONDS.sleep(2); applicationManager.stopAll(); } @Category(XSlowTests.class) @Test(timeout = 240000) public void testMultiInput() throws InterruptedException, IOException, TimeoutException { ApplicationManager applicationManager = deployApplication(JoinMultiStreamApp.class); try { applicationManager.startFlow("JoinMultiFlow"); StreamWriter s1 = applicationManager.getStreamWriter("s1"); StreamWriter s2 = applicationManager.getStreamWriter("s2"); StreamWriter s3 = applicationManager.getStreamWriter("s3"); s1.send("testing 1"); s2.send("testing 2"); s3.send("testing 3"); RuntimeMetrics terminalMetrics = RuntimeStats.getFlowletMetrics("JoinMulti", "JoinMultiFlow", "Terminal"); terminalMetrics.waitForProcessed(3, 5, TimeUnit.SECONDS); TimeUnit.SECONDS.sleep(1); ProcedureManager queryManager = applicationManager.startProcedure("Query"); Gson gson = new Gson(); ProcedureClient client = queryManager.getClient(); Assert.assertEquals("testing 1", gson.fromJson(client.query("get", ImmutableMap.of("key", "input1")), String.class)); Assert.assertEquals("testing 2", gson.fromJson(client.query("get", ImmutableMap.of("key", "input2")), String.class)); Assert.assertEquals("testing 3", gson.fromJson(client.query("get", ImmutableMap.of("key", "input3")), String.class)); } finally { applicationManager.stopAll(); } } @Category(XSlowTests.class) @Test(timeout = 360000) public void testApp() throws InterruptedException, IOException, TimeoutException { testApp(WordCountApp2.class, false, "text2"); } @Category(XSlowTests.class) @Test(timeout = 360000) public void testAppWithDatasetV2() throws InterruptedException, IOException, TimeoutException { testApp(WordCountAppV2.class, true, "text"); } @Test public void testAppwithServices() throws Exception { ApplicationManager applicationManager = deployApplication(AppWithServices.class); LOG.info("Deployed."); ServiceManager serviceManager = applicationManager.startService("NoOpService"); Assert.assertTrue(serviceManager.isRunning()); LOG.info("Service Started"); serviceManager.stop(); Assert.assertFalse(serviceManager.isRunning()); LOG.info("Service Stopped"); // we can verify metrics, by adding getServiceMetrics in RuntimeStats and then disabling the REACTOR scope test in // TestMetricsCollectionService } // todo: passing stream name as a workaround for not cleaning up streams during reset() private void testApp(Class<?> app, boolean datasetV2, String streamName) throws IOException, TimeoutException, InterruptedException { ApplicationManager applicationManager = deployApplication(app); try { applicationManager.startFlow("WordCountFlow"); // Send some inputs to streams StreamWriter streamWriter = applicationManager.getStreamWriter(streamName); for (int i = 0; i < 100; i++) { streamWriter.send(ImmutableMap.of("title", "title " + i), "testing message " + i); } // Check the flowlet metrics RuntimeMetrics flowletMetrics = RuntimeStats.getFlowletMetrics("WordCountApp", "WordCountFlow", "CountByField"); flowletMetrics.waitForProcessed(500, 10, TimeUnit.SECONDS); Assert.assertEquals(0L, flowletMetrics.getException()); // Query the result ProcedureManager procedureManager = applicationManager.startProcedure("WordFrequency"); ProcedureClient procedureClient = procedureManager.getClient(); // Verify the query result Type resultType = new TypeToken<Map<String, Long>>() { }.getType(); Gson gson = new Gson(); Map<String, Long> result = gson.fromJson(procedureClient.query("wordfreq", ImmutableMap.of("word", streamName + ":testing")), resultType); Assert.assertEquals(100L, result.get(streamName + ":testing").longValue()); // check the metrics RuntimeMetrics procedureMetrics = RuntimeStats.getProcedureMetrics("WordCountApp", "WordFrequency"); procedureMetrics.waitForProcessed(1, 5, TimeUnit.SECONDS); Assert.assertEquals(0L, procedureMetrics.getException()); // Run mapreduce job MapReduceManager mrManager = applicationManager.startMapReduce("countTotal"); mrManager.waitForFinish(180L, TimeUnit.SECONDS); long totalCount = Long.valueOf(procedureClient.query("total", Collections.<String, String>emptyMap())); // every event has 5 tokens Assert.assertEquals(5 * 100L, totalCount); // Run mapreduce from stream mrManager = applicationManager.startMapReduce("countFromStream"); mrManager.waitForFinish(120L, TimeUnit.SECONDS); totalCount = Long.valueOf(procedureClient.query("stream_total", Collections.<String, String>emptyMap())); // The stream MR only consume the body, not the header. Assert.assertEquals(3 * 100L, totalCount); // Verify by looking into dataset // todo: ugly workaround, refactor when datasets v1 gone if (!datasetV2) { DataSetManager<MyKeyValueTable> mydatasetManager = applicationManager.getDataSet("mydataset"); Assert.assertEquals(100L, Longs.fromByteArray(mydatasetManager.get().read("title:title".getBytes(Charsets.UTF_8)))); } else { DataSetManager<MyKeyValueTableDefinition.KeyValueTable> mydatasetManager = applicationManager.getDataSet("mydataset"); Assert.assertEquals(100L, Long.valueOf(mydatasetManager.get().get("title:title")).longValue()); } } finally { applicationManager.stopAll(); } } @Category(SlowTests.class) @Test public void testGenerator() throws InterruptedException, IOException, TimeoutException { ApplicationManager applicationManager = deployApplication(GenSinkApp2.class); try { applicationManager.startFlow("GenSinkFlow"); // Check the flowlet metrics RuntimeMetrics genMetrics = RuntimeStats.getFlowletMetrics("GenSinkApp", "GenSinkFlow", "GenFlowlet"); RuntimeMetrics sinkMetrics = RuntimeStats.getFlowletMetrics("GenSinkApp", "GenSinkFlow", "SinkFlowlet"); RuntimeMetrics batchSinkMetrics = RuntimeStats.getFlowletMetrics("GenSinkApp", "GenSinkFlow", "BatchSinkFlowlet"); // Generator generators 99 events + 99 batched events sinkMetrics.waitForProcessed(198, 5, TimeUnit.SECONDS); Assert.assertEquals(0L, sinkMetrics.getException()); // Batch sink only get the 99 batch events batchSinkMetrics.waitForProcessed(99, 5, TimeUnit.SECONDS); Assert.assertEquals(0L, batchSinkMetrics.getException()); Assert.assertEquals(1L, genMetrics.getException()); } finally { applicationManager.stopAll(); } } @Test public void testAppRedeployKeepsData() { ApplicationManager appManager = deployApplication(AppWithTable.class); DataSetManager<Table> myTableManager = appManager.getDataSet("my_table"); myTableManager.get().put(new Put("key1", "column1", "value1")); myTableManager.flush(); // Changes should be visible to other instances of datasets DataSetManager<Table> myTableManager2 = appManager.getDataSet("my_table"); Assert.assertEquals("value1", myTableManager2.get().get(new Get("key1", "column1")).getString("column1")); // Even after redeploy of an app: changes should be visible to other instances of datasets appManager = deployApplication(AppWithTable.class); DataSetManager<Table> myTableManager3 = appManager.getDataSet("my_table"); Assert.assertEquals("value1", myTableManager3.get().get(new Get("key1", "column1")).getString("column1")); // Calling commit again (to test we can call it multiple times) myTableManager.get().put(new Put("key1", "column1", "value2")); myTableManager.flush(); Assert.assertEquals("value1", myTableManager3.get().get(new Get("key1", "column1")).getString("column1")); } @Test (timeout = 30000L) public void testInitDataSetAccess() throws TimeoutException, InterruptedException { ApplicationManager appManager = deployApplication(DataSetInitApp.class); FlowManager flowManager = appManager.startFlow("DataSetFlow"); RuntimeMetrics flowletMetrics = RuntimeStats.getFlowletMetrics("DataSetInitApp", "DataSetFlow", "Consumer"); flowletMetrics.waitForProcessed(1, 5, TimeUnit.SECONDS); flowManager.stop(); DataSetManager<Table> dataSetManager = appManager.getDataSet("conf"); Table confTable = dataSetManager.get(); Assert.assertEquals("generator", confTable.get(new Get("key", "column")).getString("column")); dataSetManager.flush(); } @Test(timeout = 60000L) public void testAppWithAutoDeployDatasetModule() throws Exception { testAppWithDataset(AppsWithDataset.AppWithAutoDeploy.class, "MyProcedure"); } @Test(timeout = 60000L) public void testAppWithAutoDeployDataset() throws Exception { deployDatasetModule("my-kv", AppsWithDataset.KeyValueTableDefinition.Module.class); // we should be fine if module is already there. Deploy of module should not happen testAppWithDataset(AppsWithDataset.AppWithAutoDeploy.class, "MyProcedure"); } @Test(timeout = 60000L) public void testAppWithAutoCreateDataset() throws Exception { deployDatasetModule("my-kv", AppsWithDataset.KeyValueTableDefinition.Module.class); testAppWithDataset(AppsWithDataset.AppWithAutoCreate.class, "MyProcedure"); } @Test(timeout = 60000L) public void testAppWithExistingDataset() throws Exception { deployDatasetModule("my-kv", AppsWithDataset.KeyValueTableDefinition.Module.class); addDatasetInstance("myKeyValueTable", "myTable", DatasetProperties.EMPTY).create(); testAppWithDataset(AppsWithDataset.AppWithExisting.class, "MyProcedure"); } @Test(timeout = 60000L) public void testAppWithExistingDatasetInjectedByAnnotation() throws Exception { deployDatasetModule("my-kv", AppsWithDataset.KeyValueTableDefinition.Module.class); addDatasetInstance("myKeyValueTable", "myTable", DatasetProperties.EMPTY).create(); testAppWithDataset(AppsWithDataset.AppUsesAnnotation.class, "MyProcedureWithUseDataSetAnnotation"); } @Test(timeout = 60000L) public void testAppWithAutoDeployDatasetType() throws Exception { testAppWithDataset(AppsWithDataset.AppWithAutoDeployType.class, "MyProcedure"); } @Test(timeout = 60000L) public void testAppWithAutoDeployDatasetTypeShortcut() throws Exception { testAppWithDataset(AppsWithDataset.AppWithAutoDeployTypeShortcut.class, "MyProcedure"); } private void testAppWithDataset(Class<? extends Application> app, String procedureName) throws Exception { ApplicationManager applicationManager = deployApplication(app); try { // Query the result ProcedureManager procedureManager = applicationManager.startProcedure(procedureName); ProcedureClient procedureClient = procedureManager.getClient(); procedureClient.query("set", ImmutableMap.of("key", "key1", "value", "value1")); String response = procedureClient.query("get", ImmutableMap.of("key", "key1")); Assert.assertEquals("value1", new Gson().fromJson(response, String.class)); } finally { TimeUnit.SECONDS.sleep(2); applicationManager.stopAll(); } } @Test(timeout = 60000L) public void testSQLQuery() throws Exception { deployDatasetModule("my-kv", AppsWithDataset.KeyValueTableDefinition.Module.class); ApplicationManager appManager = deployApplication(AppsWithDataset.AppWithAutoCreate.class); DataSetManager<AppsWithDataset.KeyValueTableDefinition.KeyValueTable> myTableManager = appManager.getDataSet("myTable"); AppsWithDataset.KeyValueTableDefinition.KeyValueTable kvTable = myTableManager.get(); kvTable.put("a", "1"); kvTable.put("b", "2"); kvTable.put("c", "1"); myTableManager.flush(); Connection connection = getQueryClient(); try { // list the tables and make sure the table is there ResultSet results = connection.prepareStatement("show tables").executeQuery(); Assert.assertTrue(results.next()); Assert.assertTrue("continuuity_user_myTable".equalsIgnoreCase(results.getString(1))); // run a query over the dataset results = connection.prepareStatement("select first from continuuity_user_mytable where second = '1'") .executeQuery(); Assert.assertTrue(results.next()); Assert.assertEquals("a", results.getString(1)); Assert.assertTrue(results.next()); Assert.assertEquals("c", results.getString(1)); Assert.assertFalse(results.next()); } finally { connection.close(); appManager.stopAll(); } } }
unused import
continuuity-test/src/test/java/com/continuuity/test/app/TestFrameworkTest.java
unused import
Java
apache-2.0
5debc39d215c59385f97acf4e02d45703b073dd5
0
xiaojiaqiao/android-maven-plugin,CJstar/android-maven-plugin,Stuey86/android-maven-plugin,secondsun/maven-android-plugin,wskplho/android-maven-plugin,Cha0sX/android-maven-plugin,WonderCsabo/maven-android-plugin,Cha0sX/android-maven-plugin,ashutoshbhide/android-maven-plugin,hgl888/android-maven-plugin,secondsun/maven-android-plugin,WonderCsabo/maven-android-plugin,greek1979/maven-android-plugin,wskplho/android-maven-plugin,mitchhentges/android-maven-plugin,psorobka/android-maven-plugin,kedzie/maven-android-plugin,jdegroot/android-maven-plugin,greek1979/maven-android-plugin,jdegroot/android-maven-plugin,repanda/android-maven-plugin,hgl888/android-maven-plugin,xieningtao/android-maven-plugin,Cha0sX/android-maven-plugin,xiaojiaqiao/android-maven-plugin,psorobka/android-maven-plugin,CJstar/android-maven-plugin,simpligility/android-maven-plugin,Stuey86/android-maven-plugin,secondsun/maven-android-plugin,mitchhentges/android-maven-plugin,b-cuts/android-maven-plugin,xieningtao/android-maven-plugin,kedzie/maven-android-plugin,b-cuts/android-maven-plugin,ashutoshbhide/android-maven-plugin,repanda/android-maven-plugin,xiaojiaqiao/android-maven-plugin
/* * Copyright (C) 2009 Jayway AB * Copyright (C) 2007-2008 JVending Masa * * 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.jayway.maven.plugins.android.phase09package; import com.jayway.maven.plugins.android.AbstractAndroidMojo; import com.jayway.maven.plugins.android.CommandExecutor; import com.jayway.maven.plugins.android.ExecutionException; import com.jayway.maven.plugins.android.config.PullParameter; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.jar.JarArchiver; import org.codehaus.plexus.archiver.util.DefaultFileSet; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.jayway.maven.plugins.android.common.AndroidExtension.APKLIB; /** * Creates the apklib file.<br/> * apklib files do not generate deployable artifacts. * * @author nmaiorana@gmail.com * @goal apklib * @phase package * @requiresDependencyResolution compile */ public class ApklibMojo extends AbstractAndroidMojo { /** * The name of the top level folder in the APKLIB where native libraries are found. * NOTE: This is inconsistent with APK where the folder is called "lib" */ public static final String NATIVE_LIBRARIES_FOLDER = "libs"; /** * Build folder to place built native libraries into * * @parameter expression="${android.ndk.build.ndk-output-directory}" * default-value="${project.build.directory}/ndk-libs" */ private File ndkOutputDirectory; /** * Defines the architecture for the NDK build * * @parameter expression="${android.ndk.build.architecture}" default-value="armeabi" */ @PullParameter( defaultValue = "armeabi" ) private String ndkArchitecture; /** * * @throws MojoExecutionException * @throws MojoFailureException */ public void execute() throws MojoExecutionException, MojoFailureException { generateIntermediateApk(); CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( this.getLog() ); File outputFile = createApkLibraryFile(); // Set the generated .apklib file as the main artifact (because the pom states <packaging>apklib</packaging>) project.getArtifact().setFile( outputFile ); } /** * * @return * @throws MojoExecutionException */ protected File createApkLibraryFile() throws MojoExecutionException { final File apklibrary = new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + "." + APKLIB ); FileUtils.deleteQuietly( apklibrary ); try { JarArchiver jarArchiver = new JarArchiver(); jarArchiver.setDestFile( apklibrary ); jarArchiver.addFile( androidManifestFile, "AndroidManifest.xml" ); addDirectory( jarArchiver, assetsDirectory, "assets" ); addDirectory( jarArchiver, resourceDirectory, "res" ); addDirectory( jarArchiver, sourceDirectory, "src" ); addJavaResources( jarArchiver, project.getBuild().getResources(), "src" ); // Lastly, add any native libraries addNativeLibraries( jarArchiver ); jarArchiver.createArchive(); } catch ( ArchiverException e ) { throw new MojoExecutionException( "ArchiverException while creating ." + APKLIB + " file.", e ); } catch ( IOException e ) { throw new MojoExecutionException( "IOException while creating ." + APKLIB + " file.", e ); } return apklibrary; } private void addNativeLibraries( final JarArchiver jarArchiver ) throws MojoExecutionException { try { if ( nativeLibrariesDirectory.exists() ) { getLog().info( nativeLibrariesDirectory + " exists, adding libraries." ); addDirectory( jarArchiver, nativeLibrariesDirectory, NATIVE_LIBRARIES_FOLDER ); } else { getLog().info( nativeLibrariesDirectory + " does not exist, looking for libraries in target directory." ); // Add native libraries built and attached in this build final File outputDirectory = new File( project.getBuild().getDirectory() ); String prefix = NATIVE_LIBRARIES_FOLDER + "/" + ndkArchitecture; // path in archive file must have '/' addSharedLibraries( jarArchiver, outputDirectory, prefix ); // Add native library dependencies // FIXME: Remove as causes duplicate libraries when building final APK if this set includes // libraries from dependencies of the APKLIB //final File dependentLibs = new File( ndkOutputDirectory.getAbsolutePath(), ndkArchitecture ); //addSharedLibraries( jarArchiver, dependentLibs, prefix ); } } catch ( ArchiverException e ) { throw new MojoExecutionException( "IOException while creating ." + APKLIB + " file.", e ); } // TODO: Next is to check for any: // TODO: - compiled in (as part of this build) libs // TODO: - That is of course easy if the artifact is indeed attached // TODO: - If not attached, it gets a little trickier - check the target dir for any compiled .so files (generated by NDK mojo) // TODO: - But where is that directory configured? } protected void addJavaResources( JarArchiver jarArchiver, List<Resource> javaResources, String prefix ) throws IOException { for ( Resource javaResource : javaResources ) { addJavaResource( jarArchiver, javaResource, prefix ); } } /** * Adds a Java Resources directory (typically "src/main/resources") to a {@link JarArchiver}. * * @param jarArchiver * @param javaResource The Java resource to add. * @param prefix An optional prefix for where in the Jar file the directory's contents should go. * @throws IOException in case the resource path can not be resolved */ protected void addJavaResource( JarArchiver jarArchiver, Resource javaResource, String prefix ) throws IOException { if ( javaResource != null ) { final File javaResourceDirectory = new File( javaResource.getDirectory() ); if ( javaResourceDirectory.exists() ) { final String resourcePath = javaResourceDirectory.getCanonicalPath(); final String apkLibUnpackBasePath = unpackedApkLibsDirectory.getCanonicalPath(); // Don't include our dependencies' resource dirs. if ( ! resourcePath.startsWith( apkLibUnpackBasePath ) ) { final DefaultFileSet javaResourceFileSet = new DefaultFileSet(); javaResourceFileSet.setDirectory( javaResourceDirectory ); javaResourceFileSet.setPrefix( endWithSlash( prefix ) ); jarArchiver.addFileSet( javaResourceFileSet ); } } } } /** * Makes sure the string ends with "/" * * @param prefix any string, or null. * @return the prefix with a "/" at the end, never null. */ protected String endWithSlash( String prefix ) { prefix = StringUtils.defaultIfEmpty( prefix, "/" ); if ( ! prefix.endsWith( "/" ) ) { prefix = prefix + "/"; } return prefix; } /** * Adds a directory to a {@link JarArchiver} with a directory prefix. * * @param jarArchiver * @param directory The directory to add. * @param prefix An optional prefix for where in the Jar file the directory's contents should go. */ protected void addDirectory( JarArchiver jarArchiver, File directory, String prefix ) { if ( directory != null && directory.exists() ) { final DefaultFileSet fileSet = new DefaultFileSet(); fileSet.setPrefix( endWithSlash( prefix ) ); fileSet.setDirectory( directory ); jarArchiver.addFileSet( fileSet ); getLog().debug( "Added files from " + directory ); } } /** * Adds all shared libraries (.so) to a {@link JarArchiver} under 'libs'. * * @param jarArchiver The jarArchiver to add files to * @param directory The directory to scan for .so files * @param prefix The prefix for where in the jar the .so files will go. */ protected void addSharedLibraries( JarArchiver jarArchiver, File directory, String prefix ) { getLog().debug( "Searching for shared libraries in " + directory ); File[] libFiles = directory.listFiles( new FilenameFilter() { public boolean accept( final File dir, final String name ) { return name.startsWith( "lib" ) && name.endsWith( ".so" ); } } ); for ( File libFile : libFiles ) { String dest = prefix + "/" + libFile.getName(); getLog().debug( "Adding " + libFile + " as " + dest ); jarArchiver.addFile( libFile, dest ); } } /** * Generates an intermediate apk file (actually .ap_) containing the resources and assets. * * @throws MojoExecutionException */ private void generateIntermediateApk() throws MojoExecutionException { CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( this.getLog() ); File[] overlayDirectories; if ( resourceOverlayDirectories == null || resourceOverlayDirectories.length == 0 ) { overlayDirectories = new File[]{ resourceOverlayDirectory }; } else { overlayDirectories = resourceOverlayDirectories; } File androidJar = getAndroidSdk().getAndroidJar(); File outputFile = new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".ap_" ); List<String> commands = new ArrayList<String>(); commands.add( "package" ); commands.add( "-f" ); commands.add( "-M" ); commands.add( androidManifestFile.getAbsolutePath() ); for ( File resOverlayDir : overlayDirectories ) { if ( resOverlayDir != null && resOverlayDir.exists() ) { commands.add( "-S" ); commands.add( resOverlayDir.getAbsolutePath() ); } } if ( combinedRes.exists() ) { commands.add( "-S" ); commands.add( combinedRes.getAbsolutePath() ); } else { if ( resourceDirectory.exists() ) { commands.add( "-S" ); commands.add( resourceDirectory.getAbsolutePath() ); } } for ( Artifact apkLibraryArtifact : getAllRelevantDependencyArtifacts() ) { if ( apkLibraryArtifact.getType().equals( APKLIB ) ) { commands.add( "-S" ); commands.add( getLibraryUnpackDirectory( apkLibraryArtifact ) + "/res" ); } } commands.add( "--auto-add-overlay" ); if ( assetsDirectory.exists() ) { commands.add( "-A" ); commands.add( assetsDirectory.getAbsolutePath() ); } if ( extractedDependenciesAssets.exists() ) { commands.add( "-A" ); commands.add( extractedDependenciesAssets.getAbsolutePath() ); } commands.add( "-I" ); commands.add( androidJar.getAbsolutePath() ); commands.add( "-F" ); commands.add( outputFile.getAbsolutePath() ); if ( StringUtils.isNotBlank( configurations ) ) { commands.add( "-c" ); commands.add( configurations ); } getLog().info( getAndroidSdk().getPathForTool( "aapt" ) + " " + commands.toString() ); try { executor.executeCommand( getAndroidSdk().getPathForTool( "aapt" ), commands, project.getBasedir(), false ); } catch ( ExecutionException e ) { throw new MojoExecutionException( "", e ); } } }
src/main/java/com/jayway/maven/plugins/android/phase09package/ApklibMojo.java
/* * Copyright (C) 2009 Jayway AB * Copyright (C) 2007-2008 JVending Masa * * 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.jayway.maven.plugins.android.phase09package; import com.jayway.maven.plugins.android.AbstractAndroidMojo; import com.jayway.maven.plugins.android.CommandExecutor; import com.jayway.maven.plugins.android.ExecutionException; import com.jayway.maven.plugins.android.config.PullParameter; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.jar.JarArchiver; import org.codehaus.plexus.archiver.util.DefaultFileSet; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.jayway.maven.plugins.android.common.AndroidExtension.APKLIB; /** * Creates the apklib file.<br/> * apklib files do not generate deployable artifacts. * * @author nmaiorana@gmail.com * @goal apklib * @phase package * @requiresDependencyResolution compile */ public class ApklibMojo extends AbstractAndroidMojo { /** * The name of the top level folder in the APKLIB where native libraries are found. * NOTE: This is inconsistent with APK where the folder is called "lib" */ public static final String NATIVE_LIBRARIES_FOLDER = "libs"; /** * Build folder to place built native libraries into * * @parameter expression="${android.ndk.build.ndk-output-directory}" * default-value="${project.build.directory}/ndk-libs" */ private File ndkOutputDirectory; /** * Defines the architecture for the NDK build * * @parameter expression="${android.ndk.build.architecture}" default-value="armeabi" */ @PullParameter( defaultValue = "armeabi" ) private String ndkArchitecture; /** * * @throws MojoExecutionException * @throws MojoFailureException */ public void execute() throws MojoExecutionException, MojoFailureException { generateIntermediateApk(); CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( this.getLog() ); File outputFile = createApkLibraryFile(); // Set the generated .apklib file as the main artifact (because the pom states <packaging>apklib</packaging>) project.getArtifact().setFile( outputFile ); } /** * * @return * @throws MojoExecutionException */ protected File createApkLibraryFile() throws MojoExecutionException { final File apklibrary = new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + "." + APKLIB ); FileUtils.deleteQuietly( apklibrary ); try { JarArchiver jarArchiver = new JarArchiver(); jarArchiver.setDestFile( apklibrary ); jarArchiver.addFile( androidManifestFile, "AndroidManifest.xml" ); addDirectory( jarArchiver, assetsDirectory, "assets" ); addDirectory( jarArchiver, resourceDirectory, "res" ); addDirectory( jarArchiver, sourceDirectory, "src" ); addJavaResources( jarArchiver, project.getBuild().getResources(), "src" ); // Lastly, add any native libraries addNativeLibraries( jarArchiver ); jarArchiver.createArchive(); } catch ( ArchiverException e ) { throw new MojoExecutionException( "ArchiverException while creating ." + APKLIB + " file.", e ); } catch ( IOException e ) { throw new MojoExecutionException( "IOException while creating ." + APKLIB + " file.", e ); } return apklibrary; } private void addNativeLibraries( final JarArchiver jarArchiver ) throws MojoExecutionException { try { addDirectory( jarArchiver, nativeLibrariesDirectory, NATIVE_LIBRARIES_FOLDER ); // Add native libraries built in this build and dependencies final File outputDirectory = new File( project.getBuild().getDirectory() ); String prefix = NATIVE_LIBRARIES_FOLDER + "/" + ndkArchitecture; // path in archive file must have '/' addSharedLibraries( jarArchiver, outputDirectory, prefix ); final File dependentLibs = new File( ndkOutputDirectory.getAbsolutePath(), ndkArchitecture ); addSharedLibraries( jarArchiver, dependentLibs, prefix ); } catch ( ArchiverException e ) { throw new MojoExecutionException( "IOException while creating ." + APKLIB + " file.", e ); } // TODO: Next is to check for any: // TODO: - compiled in (as part of this build) libs // TODO: - That is of course easy if the artifact is indeed attached // TODO: - If not attached, it gets a little trickier - check the target dir for any compiled .so files (generated by NDK mojo) // TODO: - But where is that directory configured? } protected void addJavaResources( JarArchiver jarArchiver, List<Resource> javaResources, String prefix ) throws IOException { for ( Resource javaResource : javaResources ) { addJavaResource( jarArchiver, javaResource, prefix ); } } /** * Adds a Java Resources directory (typically "src/main/resources") to a {@link JarArchiver}. * * @param jarArchiver * @param javaResource The Java resource to add. * @param prefix An optional prefix for where in the Jar file the directory's contents should go. * @throws IOException in case the resource path can not be resolved */ protected void addJavaResource( JarArchiver jarArchiver, Resource javaResource, String prefix ) throws IOException { if ( javaResource != null ) { final File javaResourceDirectory = new File( javaResource.getDirectory() ); if ( javaResourceDirectory.exists() ) { final String resourcePath = javaResourceDirectory.getCanonicalPath(); final String apkLibUnpackBasePath = unpackedApkLibsDirectory.getCanonicalPath(); // Don't include our dependencies' resource dirs. if ( ! resourcePath.startsWith( apkLibUnpackBasePath ) ) { final DefaultFileSet javaResourceFileSet = new DefaultFileSet(); javaResourceFileSet.setDirectory( javaResourceDirectory ); javaResourceFileSet.setPrefix( endWithSlash( prefix ) ); jarArchiver.addFileSet( javaResourceFileSet ); } } } } /** * Makes sure the string ends with "/" * * @param prefix any string, or null. * @return the prefix with a "/" at the end, never null. */ protected String endWithSlash( String prefix ) { prefix = StringUtils.defaultIfEmpty( prefix, "/" ); if ( ! prefix.endsWith( "/" ) ) { prefix = prefix + "/"; } return prefix; } /** * Adds a directory to a {@link JarArchiver} with a directory prefix. * * @param jarArchiver * @param directory The directory to add. * @param prefix An optional prefix for where in the Jar file the directory's contents should go. */ protected void addDirectory( JarArchiver jarArchiver, File directory, String prefix ) { if ( directory != null && directory.exists() ) { final DefaultFileSet fileSet = new DefaultFileSet(); fileSet.setPrefix( endWithSlash( prefix ) ); fileSet.setDirectory( directory ); jarArchiver.addFileSet( fileSet ); getLog().debug( "Added files from " + directory ); } } /** * Adds all shared libraries (.so) to a {@link JarArchiver} under 'libs'. * * @param jarArchiver The jarArchiver to add files to * @param directory The directory to scan for .so files * @param prefix The prefix for where in the jar the .so files will go. */ protected void addSharedLibraries( JarArchiver jarArchiver, File directory, String prefix ) { getLog().debug( "Searching for shared libraries in " + directory ); File[] libFiles = directory.listFiles( new FilenameFilter() { public boolean accept( final File dir, final String name ) { return name.startsWith( "lib" ) && name.endsWith( ".so" ); } } ); for ( File libFile : libFiles ) { String dest = prefix + "/" + libFile.getName(); getLog().debug( "Adding " + libFile + " as " + dest ); jarArchiver.addFile( libFile, dest ); } } /** * Generates an intermediate apk file (actually .ap_) containing the resources and assets. * * @throws MojoExecutionException */ private void generateIntermediateApk() throws MojoExecutionException { CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( this.getLog() ); File[] overlayDirectories; if ( resourceOverlayDirectories == null || resourceOverlayDirectories.length == 0 ) { overlayDirectories = new File[]{ resourceOverlayDirectory }; } else { overlayDirectories = resourceOverlayDirectories; } File androidJar = getAndroidSdk().getAndroidJar(); File outputFile = new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".ap_" ); List<String> commands = new ArrayList<String>(); commands.add( "package" ); commands.add( "-f" ); commands.add( "-M" ); commands.add( androidManifestFile.getAbsolutePath() ); for ( File resOverlayDir : overlayDirectories ) { if ( resOverlayDir != null && resOverlayDir.exists() ) { commands.add( "-S" ); commands.add( resOverlayDir.getAbsolutePath() ); } } if ( combinedRes.exists() ) { commands.add( "-S" ); commands.add( combinedRes.getAbsolutePath() ); } else { if ( resourceDirectory.exists() ) { commands.add( "-S" ); commands.add( resourceDirectory.getAbsolutePath() ); } } for ( Artifact apkLibraryArtifact : getAllRelevantDependencyArtifacts() ) { if ( apkLibraryArtifact.getType().equals( APKLIB ) ) { commands.add( "-S" ); commands.add( getLibraryUnpackDirectory( apkLibraryArtifact ) + "/res" ); } } commands.add( "--auto-add-overlay" ); if ( assetsDirectory.exists() ) { commands.add( "-A" ); commands.add( assetsDirectory.getAbsolutePath() ); } if ( extractedDependenciesAssets.exists() ) { commands.add( "-A" ); commands.add( extractedDependenciesAssets.getAbsolutePath() ); } commands.add( "-I" ); commands.add( androidJar.getAbsolutePath() ); commands.add( "-F" ); commands.add( outputFile.getAbsolutePath() ); if ( StringUtils.isNotBlank( configurations ) ) { commands.add( "-c" ); commands.add( configurations ); } getLog().info( getAndroidSdk().getPathForTool( "aapt" ) + " " + commands.toString() ); try { executor.executeCommand( getAndroidSdk().getPathForTool( "aapt" ), commands, project.getBasedir(), false ); } catch ( ExecutionException e ) { throw new MojoExecutionException( "", e ); } } }
Change APKLIB file set so that: - we only search for more library files if nativeLibrariesDirectory doesn't exist - don't add dependent libraries as these will be pulled in directly by final APK pom
src/main/java/com/jayway/maven/plugins/android/phase09package/ApklibMojo.java
Change APKLIB file set so that: - we only search for more library files if nativeLibrariesDirectory doesn't exist - don't add dependent libraries as these will be pulled in directly by final APK pom
Java
apache-2.0
69dda2c9d000254c198544b25451389666a99b57
0
perezd/bazel,ButterflyNetwork/bazel,perezd/bazel,cushon/bazel,katre/bazel,perezd/bazel,perezd/bazel,cushon/bazel,perezd/bazel,cushon/bazel,cushon/bazel,ButterflyNetwork/bazel,cushon/bazel,bazelbuild/bazel,ButterflyNetwork/bazel,bazelbuild/bazel,katre/bazel,ButterflyNetwork/bazel,ButterflyNetwork/bazel,bazelbuild/bazel,perezd/bazel,bazelbuild/bazel,katre/bazel,cushon/bazel,katre/bazel,ButterflyNetwork/bazel,katre/bazel,bazelbuild/bazel,perezd/bazel,katre/bazel,bazelbuild/bazel
// Copyright 2017 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.analysis.config; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Multimap; import com.google.devtools.build.lib.analysis.ConfigurationsCollector; import com.google.devtools.build.lib.analysis.ConfigurationsResult; import com.google.devtools.build.lib.analysis.Dependency; import com.google.devtools.build.lib.analysis.DependencyKey; import com.google.devtools.build.lib.analysis.DependencyKind; import com.google.devtools.build.lib.analysis.PlatformOptions; import com.google.devtools.build.lib.analysis.TargetAndConfiguration; import com.google.devtools.build.lib.analysis.config.transitions.ConfigurationTransition; import com.google.devtools.build.lib.analysis.config.transitions.NullTransition; import com.google.devtools.build.lib.analysis.config.transitions.SplitTransition; import com.google.devtools.build.lib.analysis.config.transitions.TransitionFactory; import com.google.devtools.build.lib.analysis.config.transitions.TransitionUtil; import com.google.devtools.build.lib.analysis.starlark.StarlarkTransition; import com.google.devtools.build.lib.analysis.starlark.StarlarkTransition.TransitionException; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.events.ExtendedEventHandler; import com.google.devtools.build.lib.events.StoredEventHandler; import com.google.devtools.build.lib.packages.Attribute; import com.google.devtools.build.lib.packages.AttributeTransitionData; import com.google.devtools.build.lib.packages.ConfiguredAttributeMapper; import com.google.devtools.build.lib.packages.Target; import com.google.devtools.build.lib.skyframe.BuildConfigurationValue; import com.google.devtools.build.lib.skyframe.PackageValue; import com.google.devtools.build.lib.skyframe.PlatformMappingValue; import com.google.devtools.build.lib.util.OrderedSetMultimap; import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.build.skyframe.SkyFunction; import com.google.devtools.build.skyframe.SkyKey; import com.google.devtools.build.skyframe.ValueOrException; import com.google.devtools.common.options.OptionsParsingException; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * Turns configuration transition requests into actual configurations. * * <p>This involves: * * <ol> * <li>Patching a source configuration's options with the transition. * <li>Getting the destination configuration from Skyframe. * </ol> * * <p>For the work of determining the transition requests themselves, see {@link * TransitionResolver}. */ public final class ConfigurationResolver { /** * Determines the output ordering of each {@code <attribute, depLabel> -> [dep<config1>, * dep<config2>, ...]} collection produced by a split transition. */ @VisibleForTesting public static final Comparator<Dependency> SPLIT_DEP_ORDERING = Comparator.comparing( Functions.compose(BuildConfiguration::getMnemonic, Dependency::getConfiguration)) .thenComparing( Functions.compose(BuildConfiguration::checksum, Dependency::getConfiguration)); private final SkyFunction.Environment env; private final TargetAndConfiguration ctgValue; private final BuildConfiguration hostConfiguration; private final ImmutableMap<Label, ConfigMatchingProvider> configConditions; public ConfigurationResolver( SkyFunction.Environment env, TargetAndConfiguration ctgValue, BuildConfiguration hostConfiguration, ImmutableMap<Label, ConfigMatchingProvider> configConditions) { this.env = env; this.ctgValue = ctgValue; this.hostConfiguration = hostConfiguration; this.configConditions = configConditions; } private BuildConfiguration getCurrentConfiguration() { return ctgValue.getConfiguration(); } /** * Translates a set of {@link DependencyKey} objects with configuration transition requests to the * same objects with resolved configurations. * * <p>This method must preserve the original label ordering of each attribute. For example, if * {@code dependencyKeys.get("data")} is {@code [":a", ":b"]}, the resolved variant must also be * {@code [":a", ":b"]} in the same order. * * <p>For split transitions, {@code dependencyKeys.get("data") = [":a", ":b"]} can produce the * output {@code [":a"<config1>, ":a"<config2>, ..., ":b"<config1>, ":b"<config2>, ...]}. All * instances of ":a" still appear before all instances of ":b". But the {@code [":a"<config1>, * ":a"<config2>"]} subset may be in any (deterministic) order. In particular, this may not be the * same order as {@link SplitTransition#split}. If needed, this code can be modified to use that * order, but that involves more runtime in performance-critical code, so we won't make that * change without a clear need. * * <p>These configurations unconditionally include all fragments. * * <p>This method is heavily performance-optimized. Because {@link * com.google.devtools.build.lib.skyframe.ConfiguredTargetFunction} calls it over every edge in * the configured target graph, small inefficiencies can have observable impact on analysis time. * Keep this in mind when making modifications and performance-test any changes you make. * * @param dependencyKeys the transition requests for each dep and each dependency kind * @return a mapping from each dependency kind in the source target to the {@link * BuildConfiguration}s and {@link Label}s for the deps under that dependency kind . Returns * null if not all Skyframe dependencies are available. */ @Nullable public OrderedSetMultimap<DependencyKind, Dependency> resolveConfigurations( OrderedSetMultimap<DependencyKind, DependencyKey> dependencyKeys) throws DependencyEvaluationException, InterruptedException { OrderedSetMultimap<DependencyKind, Dependency> resolvedDeps = OrderedSetMultimap.create(); boolean needConfigsFromSkyframe = false; for (Map.Entry<DependencyKind, DependencyKey> entry : dependencyKeys.entries()) { DependencyKind dependencyKind = entry.getKey(); DependencyKey dependencyKey = entry.getValue(); ImmutableList<Dependency> depConfig = resolveConfiguration(dependencyKind, dependencyKey); if (depConfig == null) { // Instead of returning immediately, give the loop a chance to queue up every missing // dependency, then return all at once. That prevents re-executing this code an unnecessary // number of times. i.e. this is equivalent to calling env.getValues() once over all deps. needConfigsFromSkyframe = true; } else { resolvedDeps.putAll(dependencyKind, depConfig); } } return needConfigsFromSkyframe ? null : resolvedDeps; } @Nullable private ImmutableList<Dependency> resolveConfiguration( DependencyKind dependencyKind, DependencyKey dependencyKey) throws DependencyEvaluationException, InterruptedException { Dependency.Builder dependencyBuilder = dependencyKey.getDependencyBuilder(); ConfigurationTransition transition = dependencyKey.getTransition(); if (transition == NullTransition.INSTANCE) { return ImmutableList.of(resolveNullTransition(dependencyBuilder, dependencyKind)); } else if (transition.isHostTransition()) { return ImmutableList.of(resolveHostTransition(dependencyBuilder, dependencyKey)); } return resolveGenericTransition( getCurrentConfiguration().fragmentClasses(), dependencyBuilder, dependencyKey); } @Nullable private Dependency resolveNullTransition( Dependency.Builder dependencyBuilder, DependencyKind dependencyKind) throws DependencyEvaluationException, InterruptedException { // The null configuration can be trivially computed (it's, well, null), so special-case that // transition here and skip the rest of the logic. A *lot* of targets have null deps, so // this produces real savings. Profiling tests over a simple cc_binary show this saves ~1% of // total analysis phase time. if (dependencyKind.getAttribute() != null) { ImmutableList<String> transitionKeys = collectTransitionKeys(dependencyKind.getAttribute()); if (transitionKeys == null) { return null; // Need Skyframe deps. } dependencyBuilder.setTransitionKeys(transitionKeys); } return dependencyBuilder.withNullConfiguration().build(); } private Dependency resolveHostTransition( Dependency.Builder dependencyBuilder, DependencyKey dependencyKey) { return dependencyBuilder .setConfiguration(hostConfiguration) .setAspects(dependencyKey.getAspects()) .build(); } @Nullable private ImmutableList<Dependency> resolveGenericTransition( FragmentClassSet depFragments, Dependency.Builder dependencyBuilder, DependencyKey dependencyKey) throws DependencyEvaluationException, InterruptedException { Map<String, BuildOptions> toOptions; try { toOptions = applyTransitionWithSkyframe( getCurrentConfiguration().getOptions(), dependencyKey.getTransition(), env, env.getListener()); if (toOptions == null) { return null; // Need more Skyframe deps for a Starlark transition. } } catch (TransitionException e) { throw new DependencyEvaluationException(e); } if (depFragments.equals(getCurrentConfiguration().fragmentClasses()) && SplitTransition.equals(getCurrentConfiguration().getOptions(), toOptions.values())) { // The dep uses the same exact configuration. Let's re-use the current configuration and // skip adding a Skyframe dependency edge on it. return ImmutableList.of( dependencyBuilder .setConfiguration(getCurrentConfiguration()) .setAspects(dependencyKey.getAspects()) // Explicitly do not set the transition key, since there is only one configuration // and it matches the current one. This ignores the transition key set if this // was a split transition. .build()); } PathFragment platformMappingPath = getCurrentConfiguration().getOptions().get(PlatformOptions.class).platformMappings; PlatformMappingValue platformMappingValue = (PlatformMappingValue) env.getValue(PlatformMappingValue.Key.create(platformMappingPath)); if (platformMappingValue == null) { return null; // Need platform mappings from Skyframe. } Map<String, BuildConfigurationValue.Key> configurationKeys = new HashMap<>(); try { for (Map.Entry<String, BuildOptions> optionsEntry : toOptions.entrySet()) { String transitionKey = optionsEntry.getKey(); BuildConfigurationValue.Key buildConfigurationValueKey = BuildConfigurationValue.keyWithPlatformMapping( platformMappingValue, depFragments, optionsEntry.getValue()); configurationKeys.put(transitionKey, buildConfigurationValueKey); } } catch (OptionsParsingException e) { throw new DependencyEvaluationException(new InvalidConfigurationException(e)); } Map<SkyKey, ValueOrException<InvalidConfigurationException>> depConfigValues = env.getValuesOrThrow(configurationKeys.values(), InvalidConfigurationException.class); List<Dependency> dependencies = new ArrayList<>(); try { for (Map.Entry<String, BuildConfigurationValue.Key> entry : configurationKeys.entrySet()) { String transitionKey = entry.getKey(); ValueOrException<InvalidConfigurationException> valueOrException = depConfigValues.get(entry.getValue()); if (valueOrException.get() == null) { continue; } BuildConfiguration configuration = ((BuildConfigurationValue) valueOrException.get()).getConfiguration(); if (configuration != null) { Dependency resolvedDep = dependencyBuilder // Copy the builder so we don't overwrite the other dependencies. .copy() .setConfiguration(configuration) .setAspects(dependencyKey.getAspects()) .setTransitionKey(transitionKey) .build(); dependencies.add(resolvedDep); } } if (env.valuesMissing()) { return null; // Need dependency configurations. } } catch (InvalidConfigurationException e) { throw new DependencyEvaluationException(e); } return ImmutableList.sortedCopyOf(SPLIT_DEP_ORDERING, dependencies); } @Nullable private ImmutableList<String> collectTransitionKeys(Attribute attribute) throws DependencyEvaluationException, InterruptedException { TransitionFactory<AttributeTransitionData> transitionFactory = attribute.getTransitionFactory(); if (transitionFactory.isSplit()) { AttributeTransitionData transitionData = AttributeTransitionData.builder() .attributes( ConfiguredAttributeMapper.of( ctgValue.getTarget().getAssociatedRule(), configConditions, ctgValue.getConfiguration().checksum())) .build(); ConfigurationTransition baseTransition = transitionFactory.create(transitionData); Map<String, BuildOptions> toOptions; try { toOptions = applyTransitionWithSkyframe( getCurrentConfiguration().getOptions(), baseTransition, env, env.getListener()); if (toOptions == null) { return null; // Need more Skyframe deps for a Starlark transition. } } catch (TransitionException e) { throw new DependencyEvaluationException(e); } if (!SplitTransition.equals(getCurrentConfiguration().getOptions(), toOptions.values())) { return ImmutableList.copyOf(toOptions.keySet()); } } return ImmutableList.of(); } /** * Applies a configuration transition over a set of build options. * * <p>This is only for callers that can't use {@link #applyTransitionWithSkyframe}. The difference * is {@link #applyTransitionWithSkyframe} internally computes {@code buildSettingPackages} with * Skyframe, while this version requires it as a precomputed input. * * <p>prework - load all default values for reading build settings in Starlark transitions (by * design, {@link BuildOptions} never holds default values of build settings) * * <p>postwork - replay events/throw errors from transition implementation function and validate * the outputs of the transition. This only applies to Starlark transitions. * * @return the build options for the transitioned configuration. */ public static Map<String, BuildOptions> applyTransitionWithoutSkyframe( BuildOptions fromOptions, ConfigurationTransition transition, Map<PackageValue.Key, PackageValue> buildSettingPackages, ExtendedEventHandler eventHandler) throws TransitionException, InterruptedException { if (StarlarkTransition.doesStarlarkTransition(transition)) { return applyStarlarkTransition(fromOptions, transition, buildSettingPackages, eventHandler); } return transition.apply(TransitionUtil.restrict(transition, fromOptions), eventHandler); } /** * Applies a configuration transition over a set of build options. * * <p>Callers should use this over {@link #applyTransitionWithoutSkyframe}. Unlike that variation, * this would may return null if it needs more Skyframe deps. * * <p>postwork - replay events/throw errors from transition implementation function and validate * the outputs of the transition. This only applies to Starlark transitions. * * @return the build options for the transitioned configuration, or null if Skyframe dependencies * for build_setting default values for Starlark transitions. These can be read from their * respective packages. */ @Nullable public static Map<String, BuildOptions> applyTransitionWithSkyframe( BuildOptions fromOptions, ConfigurationTransition transition, SkyFunction.Environment env, ExtendedEventHandler eventHandler) throws TransitionException, InterruptedException { if (StarlarkTransition.doesStarlarkTransition(transition)) { // TODO(blaze-team): find a way to dedupe this with SkyframeExecutor.getBuildSettingPackages. Map<PackageValue.Key, PackageValue> buildSettingPackages = StarlarkTransition.getBuildSettingPackages(env, transition); return buildSettingPackages == null ? null : applyStarlarkTransition(fromOptions, transition, buildSettingPackages, eventHandler); } return transition.apply(TransitionUtil.restrict(transition, fromOptions), eventHandler); } /** * Applies a Starlark transition. * * @param fromOptions source options before the transition * @param transition the transition itself * @param buildSettingPackages packages for build_settings read by the transition. This is used to * read default values for build_settings that aren't explicitly set on the build. * @param eventHandler handler for errors evaluating the transition. * @return transition output */ private static Map<String, BuildOptions> applyStarlarkTransition( BuildOptions fromOptions, ConfigurationTransition transition, Map<PackageValue.Key, PackageValue> buildSettingPackages, ExtendedEventHandler eventHandler) throws TransitionException, InterruptedException { fromOptions = StarlarkTransition.addDefaultStarlarkOptions(fromOptions, transition, buildSettingPackages); // TODO(bazel-team): Add safety-check that this never mutates fromOptions. StoredEventHandler handlerWithErrorStatus = new StoredEventHandler(); Map<String, BuildOptions> result = transition.apply(TransitionUtil.restrict(transition, fromOptions), handlerWithErrorStatus); // We use a temporary StoredEventHandler instead of the caller's event handler because // StarlarkTransition.validate assumes no errors occurred. We need a StoredEventHandler to be // able to check that, and fail out early if there are errors. // // TODO(bazel-team): harden StarlarkTransition.validate so we can eliminate this step. // StarlarkRuleTransitionProviderTest#testAliasedBuildSetting_outputReturnMismatch shows the // effect. handlerWithErrorStatus.replayOn(eventHandler); if (handlerWithErrorStatus.hasErrors()) { throw new TransitionException("Errors encountered while applying Starlark transition"); } result = StarlarkTransition.validate(transition, buildSettingPackages, result); return result; } /** * This method allows resolution of configurations outside of a skyfunction call. * * <p>Unlike {@link #resolveConfigurations}, this doesn't expect the current context to be * evaluating dependencies of a parent target. So this method is also suitable for top-level * targets. * * <p>Resolution consists of applying the per-target transitions specified in {@code * targetsToEvaluate}. This can be used, e.g., to apply {@link * com.google.devtools.build.lib.analysis.config.transitions.TransitionFactory}s over global * top-level configurations. * * <p>Preserves the original input order (but merges duplicate nodes that might occur due to * top-level configuration transitions) . Uses original (untrimmed, pre-transition) configurations * for targets that can't be evaluated (e.g. due to loading phase errors). * * <p>This is suitable for feeding {@link * com.google.devtools.build.lib.analysis.ConfiguredTargetValue} keys: as general principle {@link * com.google.devtools.build.lib.analysis.ConfiguredTarget}s should have exactly as much * information in their configurations as they need to evaluate and no more (e.g. there's no need * for Android settings in a C++ configured target). * * @param defaultContext the original targets and starting configurations before applying rule * transitions and trimming. When actual configurations can't be evaluated, these values are * returned as defaults. See TODO below. * @param targetsToEvaluate the inputs repackaged as dependencies, including rule-specific * transitions * @param eventHandler the error event handler * @param configurationsCollector the collector which finds configurations for dependencies */ // TODO(bazel-team): error out early for targets that fail - failed configuration evaluations // should never make it through analysis (and especially not seed ConfiguredTargetValues) // TODO(gregce): merge this more with resolveConfigurations? One crucial difference is // resolveConfigurations can null-return on missing deps since it executes inside Skyfunctions. // Keep this in sync with {@link PrepareAnalysisPhaseFunction#resolveConfigurations}. public static TopLevelTargetsAndConfigsResult getConfigurationsFromExecutor( Iterable<TargetAndConfiguration> defaultContext, Multimap<BuildConfiguration, DependencyKey> targetsToEvaluate, ExtendedEventHandler eventHandler, ConfigurationsCollector configurationsCollector) throws InvalidConfigurationException, InterruptedException { Map<Label, Target> labelsToTargets = new HashMap<>(); for (TargetAndConfiguration targetAndConfig : defaultContext) { labelsToTargets.put(targetAndConfig.getLabel(), targetAndConfig.getTarget()); } // Maps <target, originalConfig> pairs to <target, finalConfig> pairs for targets that // could be successfully Skyframe-evaluated. Map<TargetAndConfiguration, TargetAndConfiguration> successfullyEvaluatedTargets = new LinkedHashMap<>(); boolean hasError = false; if (!targetsToEvaluate.isEmpty()) { for (BuildConfiguration fromConfig : targetsToEvaluate.keySet()) { ConfigurationsResult configurationsResult = configurationsCollector.getConfigurations( eventHandler, fromConfig.getOptions(), targetsToEvaluate.get(fromConfig)); hasError |= configurationsResult.hasError(); for (Map.Entry<DependencyKey, BuildConfiguration> evaluatedTarget : configurationsResult.getConfigurationMap().entries()) { Target target = labelsToTargets.get(evaluatedTarget.getKey().getLabel()); successfullyEvaluatedTargets.put( new TargetAndConfiguration(target, fromConfig), new TargetAndConfiguration(target, evaluatedTarget.getValue())); } } } LinkedHashSet<TargetAndConfiguration> result = new LinkedHashSet<>(); for (TargetAndConfiguration originalInput : defaultContext) { // If the configuration couldn't be determined (e.g. loading phase error), use the original. result.add(successfullyEvaluatedTargets.getOrDefault(originalInput, originalInput)); } return new TopLevelTargetsAndConfigsResult(result, hasError); } /** * The result of {@link #getConfigurationsFromExecutor} which also registers if an error was * recorded. */ public static class TopLevelTargetsAndConfigsResult { private final Collection<TargetAndConfiguration> configurations; private final boolean hasError; public TopLevelTargetsAndConfigsResult( Collection<TargetAndConfiguration> configurations, boolean hasError) { this.configurations = configurations; this.hasError = hasError; } public boolean hasError() { return hasError; } public Collection<TargetAndConfiguration> getTargetsAndConfigs() { return configurations; } } }
src/main/java/com/google/devtools/build/lib/analysis/config/ConfigurationResolver.java
// Copyright 2017 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.analysis.config; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Multimap; import com.google.devtools.build.lib.analysis.ConfigurationsCollector; import com.google.devtools.build.lib.analysis.ConfigurationsResult; import com.google.devtools.build.lib.analysis.Dependency; import com.google.devtools.build.lib.analysis.DependencyKey; import com.google.devtools.build.lib.analysis.DependencyKind; import com.google.devtools.build.lib.analysis.PlatformOptions; import com.google.devtools.build.lib.analysis.TargetAndConfiguration; import com.google.devtools.build.lib.analysis.config.transitions.ConfigurationTransition; import com.google.devtools.build.lib.analysis.config.transitions.NullTransition; import com.google.devtools.build.lib.analysis.config.transitions.SplitTransition; import com.google.devtools.build.lib.analysis.config.transitions.TransitionFactory; import com.google.devtools.build.lib.analysis.config.transitions.TransitionUtil; import com.google.devtools.build.lib.analysis.starlark.StarlarkTransition; import com.google.devtools.build.lib.analysis.starlark.StarlarkTransition.TransitionException; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.events.ExtendedEventHandler; import com.google.devtools.build.lib.events.StoredEventHandler; import com.google.devtools.build.lib.packages.Attribute; import com.google.devtools.build.lib.packages.AttributeTransitionData; import com.google.devtools.build.lib.packages.ConfiguredAttributeMapper; import com.google.devtools.build.lib.packages.Target; import com.google.devtools.build.lib.skyframe.BuildConfigurationValue; import com.google.devtools.build.lib.skyframe.PackageValue; import com.google.devtools.build.lib.skyframe.PlatformMappingValue; import com.google.devtools.build.lib.util.OrderedSetMultimap; import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.build.skyframe.SkyFunction; import com.google.devtools.build.skyframe.SkyKey; import com.google.devtools.build.skyframe.ValueOrException; import com.google.devtools.common.options.OptionsParsingException; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * Turns configuration transition requests into actual configurations. * * <p>This involves: * * <ol> * <li>Patching a source configuration's options with the transition. * <li>Getting the destination configuration from Skyframe. * </ol> * * <p>For the work of determining the transition requests themselves, see {@link * TransitionResolver}. */ public final class ConfigurationResolver { /** * Determines the output ordering of each {@code <attribute, depLabel> -> [dep<config1>, * dep<config2>, ...]} collection produced by a split transition. */ @VisibleForTesting public static final Comparator<Dependency> SPLIT_DEP_ORDERING = Comparator.comparing( Functions.compose(BuildConfiguration::getMnemonic, Dependency::getConfiguration)) .thenComparing( Functions.compose(BuildConfiguration::checksum, Dependency::getConfiguration)); // Signals that a Skyframe restart is needed. private static class ValueMissingException extends Exception { private ValueMissingException() { super(); } } private final SkyFunction.Environment env; private final TargetAndConfiguration ctgValue; private final BuildConfiguration hostConfiguration; private final ImmutableMap<Label, ConfigMatchingProvider> configConditions; public ConfigurationResolver( SkyFunction.Environment env, TargetAndConfiguration ctgValue, BuildConfiguration hostConfiguration, ImmutableMap<Label, ConfigMatchingProvider> configConditions) { this.env = env; this.ctgValue = ctgValue; this.hostConfiguration = hostConfiguration; this.configConditions = configConditions; } private BuildConfiguration getCurrentConfiguration() { return ctgValue.getConfiguration(); } /** * Translates a set of {@link DependencyKey} objects with configuration transition requests to the * same objects with resolved configurations. * * <p>This method must preserve the original label ordering of each attribute. For example, if * {@code dependencyKeys.get("data")} is {@code [":a", ":b"]}, the resolved variant must also be * {@code [":a", ":b"]} in the same order. * * <p>For split transitions, {@code dependencyKeys.get("data") = [":a", ":b"]} can produce the * output {@code [":a"<config1>, ":a"<config2>, ..., ":b"<config1>, ":b"<config2>, ...]}. All * instances of ":a" still appear before all instances of ":b". But the {@code [":a"<config1>, * ":a"<config2>"]} subset may be in any (deterministic) order. In particular, this may not be the * same order as {@link SplitTransition#split}. If needed, this code can be modified to use that * order, but that involves more runtime in performance-critical code, so we won't make that * change without a clear need. * * <p>These configurations unconditionally include all fragments. * * <p>This method is heavily performance-optimized. Because {@link * com.google.devtools.build.lib.skyframe.ConfiguredTargetFunction} calls it over every edge in * the configured target graph, small inefficiencies can have observable impact on analysis time. * Keep this in mind when making modifications and performance-test any changes you make. * * @param dependencyKeys the transition requests for each dep and each dependency kind * @return a mapping from each dependency kind in the source target to the {@link * BuildConfiguration}s and {@link Label}s for the deps under that dependency kind . Returns * null if not all Skyframe dependencies are available. */ @Nullable public OrderedSetMultimap<DependencyKind, Dependency> resolveConfigurations( OrderedSetMultimap<DependencyKind, DependencyKey> dependencyKeys) throws DependencyEvaluationException, InterruptedException { try { OrderedSetMultimap<DependencyKind, Dependency> resolvedDeps = OrderedSetMultimap.create(); for (Map.Entry<DependencyKind, DependencyKey> entry : dependencyKeys.entries()) { DependencyKind dependencyKind = entry.getKey(); DependencyKey dependencyKey = entry.getValue(); resolvedDeps.putAll(dependencyKind, resolveConfiguration(dependencyKind, dependencyKey)); } return resolvedDeps; } catch (ValueMissingException e) { return null; } } private ImmutableList<Dependency> resolveConfiguration( DependencyKind dependencyKind, DependencyKey dependencyKey) throws DependencyEvaluationException, ValueMissingException, InterruptedException { Dependency.Builder dependencyBuilder = dependencyKey.getDependencyBuilder(); ConfigurationTransition transition = dependencyKey.getTransition(); if (transition == NullTransition.INSTANCE) { return ImmutableList.of(resolveNullTransition(dependencyBuilder, dependencyKind)); } else if (transition.isHostTransition()) { return ImmutableList.of(resolveHostTransition(dependencyBuilder, dependencyKey)); } return resolveGenericTransition( getCurrentConfiguration().fragmentClasses(), dependencyBuilder, dependencyKey); } private Dependency resolveNullTransition( Dependency.Builder dependencyBuilder, DependencyKind dependencyKind) throws DependencyEvaluationException, ValueMissingException, InterruptedException { // The null configuration can be trivially computed (it's, well, null), so special-case that // transition here and skip the rest of the logic. A *lot* of targets have null deps, so // this produces real savings. Profiling tests over a simple cc_binary show this saves ~1% of // total analysis phase time. if (dependencyKind.getAttribute() != null) { dependencyBuilder.setTransitionKeys(collectTransitionKeys(dependencyKind.getAttribute())); } return dependencyBuilder.withNullConfiguration().build(); } private Dependency resolveHostTransition( Dependency.Builder dependencyBuilder, DependencyKey dependencyKey) { return dependencyBuilder .setConfiguration(hostConfiguration) .setAspects(dependencyKey.getAspects()) .build(); } private ImmutableList<Dependency> resolveGenericTransition( FragmentClassSet depFragments, Dependency.Builder dependencyBuilder, DependencyKey dependencyKey) throws DependencyEvaluationException, InterruptedException, ValueMissingException { Map<String, BuildOptions> toOptions; try { toOptions = applyTransitionWithSkyframe( getCurrentConfiguration().getOptions(), dependencyKey.getTransition(), env, env.getListener()); if (toOptions == null) { // TODO(b/192000405): refactor this into a simple null return. We don't need to trigger // exceptions for standard control flow. throw new ValueMissingException(); // Need more Skyframe deps for a Starlark transition. } } catch (TransitionException e) { throw new DependencyEvaluationException(e); } if (depFragments.equals(getCurrentConfiguration().fragmentClasses()) && SplitTransition.equals(getCurrentConfiguration().getOptions(), toOptions.values())) { // The dep uses the same exact configuration. Let's re-use the current configuration and // skip adding a Skyframe dependency edge on it. return ImmutableList.of( dependencyBuilder .setConfiguration(getCurrentConfiguration()) .setAspects(dependencyKey.getAspects()) // Explicitly do not set the transition key, since there is only one configuration // and it matches the current one. This ignores the transition key set if this // was a split transition. .build()); } PathFragment platformMappingPath = getCurrentConfiguration().getOptions().get(PlatformOptions.class).platformMappings; PlatformMappingValue platformMappingValue = (PlatformMappingValue) env.getValue(PlatformMappingValue.Key.create(platformMappingPath)); if (platformMappingValue == null) { throw new ValueMissingException(); } Map<String, BuildConfigurationValue.Key> configurationKeys = new HashMap<>(); try { for (Map.Entry<String, BuildOptions> optionsEntry : toOptions.entrySet()) { String transitionKey = optionsEntry.getKey(); BuildConfigurationValue.Key buildConfigurationValueKey = BuildConfigurationValue.keyWithPlatformMapping( platformMappingValue, depFragments, optionsEntry.getValue()); configurationKeys.put(transitionKey, buildConfigurationValueKey); } } catch (OptionsParsingException e) { throw new DependencyEvaluationException(new InvalidConfigurationException(e)); } Map<SkyKey, ValueOrException<InvalidConfigurationException>> depConfigValues = env.getValuesOrThrow(configurationKeys.values(), InvalidConfigurationException.class); List<Dependency> dependencies = new ArrayList<>(); try { for (Map.Entry<String, BuildConfigurationValue.Key> entry : configurationKeys.entrySet()) { String transitionKey = entry.getKey(); ValueOrException<InvalidConfigurationException> valueOrException = depConfigValues.get(entry.getValue()); if (valueOrException.get() == null) { continue; } BuildConfiguration configuration = ((BuildConfigurationValue) valueOrException.get()).getConfiguration(); if (configuration != null) { Dependency resolvedDep = dependencyBuilder // Copy the builder so we don't overwrite the other dependencies. .copy() .setConfiguration(configuration) .setAspects(dependencyKey.getAspects()) .setTransitionKey(transitionKey) .build(); dependencies.add(resolvedDep); } } if (env.valuesMissing()) { throw new ValueMissingException(); } } catch (InvalidConfigurationException e) { throw new DependencyEvaluationException(e); } return ImmutableList.sortedCopyOf(SPLIT_DEP_ORDERING, dependencies); } private ImmutableList<String> collectTransitionKeys(Attribute attribute) throws DependencyEvaluationException, ValueMissingException, InterruptedException { TransitionFactory<AttributeTransitionData> transitionFactory = attribute.getTransitionFactory(); if (transitionFactory.isSplit()) { AttributeTransitionData transitionData = AttributeTransitionData.builder() .attributes( ConfiguredAttributeMapper.of( ctgValue.getTarget().getAssociatedRule(), configConditions, ctgValue.getConfiguration().checksum())) .build(); ConfigurationTransition baseTransition = transitionFactory.create(transitionData); Map<String, BuildOptions> toOptions; try { toOptions = applyTransitionWithSkyframe( getCurrentConfiguration().getOptions(), baseTransition, env, env.getListener()); if (toOptions == null) { throw new ValueMissingException(); // Need more Skyframe deps for a Starlark transition. } } catch (TransitionException e) { throw new DependencyEvaluationException(e); } if (!SplitTransition.equals(getCurrentConfiguration().getOptions(), toOptions.values())) { return ImmutableList.copyOf(toOptions.keySet()); } } return ImmutableList.of(); } /** * Applies a configuration transition over a set of build options. * * <p>This is only for callers that can't use {@link #applyTransitionWithSkyframe}. The difference * is {@link #applyTransitionWithSkyframe} internally computes {@code buildSettingPackages} with * Skyframe, while this version requires it as a precomputed input. * * <p>prework - load all default values for reading build settings in Starlark transitions (by * design, {@link BuildOptions} never holds default values of build settings) * * <p>postwork - replay events/throw errors from transition implementation function and validate * the outputs of the transition. This only applies to Starlark transitions. * * @return the build options for the transitioned configuration. */ public static Map<String, BuildOptions> applyTransitionWithoutSkyframe( BuildOptions fromOptions, ConfigurationTransition transition, Map<PackageValue.Key, PackageValue> buildSettingPackages, ExtendedEventHandler eventHandler) throws TransitionException, InterruptedException { if (StarlarkTransition.doesStarlarkTransition(transition)) { return applyStarlarkTransition(fromOptions, transition, buildSettingPackages, eventHandler); } return transition.apply(TransitionUtil.restrict(transition, fromOptions), eventHandler); } /** * Applies a configuration transition over a set of build options. * * <p>Callers should use this over {@link #applyTransitionWithoutSkyframe}. Unlike that variation, * this would may return null if it needs more Skyframe deps. * * <p>postwork - replay events/throw errors from transition implementation function and validate * the outputs of the transition. This only applies to Starlark transitions. * * @return the build options for the transitioned configuration, or null if Skyframe dependencies * for build_setting default values for Starlark transitions. These can be read from their * respective packages. */ @Nullable public static Map<String, BuildOptions> applyTransitionWithSkyframe( BuildOptions fromOptions, ConfigurationTransition transition, SkyFunction.Environment env, ExtendedEventHandler eventHandler) throws TransitionException, InterruptedException { if (StarlarkTransition.doesStarlarkTransition(transition)) { // TODO(blaze-team): find a way to dedupe this with SkyframeExecutor.getBuildSettingPackages. Map<PackageValue.Key, PackageValue> buildSettingPackages = StarlarkTransition.getBuildSettingPackages(env, transition); return buildSettingPackages == null ? null : applyStarlarkTransition(fromOptions, transition, buildSettingPackages, eventHandler); } return transition.apply(TransitionUtil.restrict(transition, fromOptions), eventHandler); } /** * Applies a Starlark transition. * * @param fromOptions source options before the transition * @param transition the transition itself * @param buildSettingPackages packages for build_settings read by the transition. This is used to * read default values for build_settings that aren't explicitly set on the build. * @param eventHandler handler for errors evaluating the transition. * @return transition output */ private static Map<String, BuildOptions> applyStarlarkTransition( BuildOptions fromOptions, ConfigurationTransition transition, Map<PackageValue.Key, PackageValue> buildSettingPackages, ExtendedEventHandler eventHandler) throws TransitionException, InterruptedException { fromOptions = StarlarkTransition.addDefaultStarlarkOptions(fromOptions, transition, buildSettingPackages); // TODO(bazel-team): Add safety-check that this never mutates fromOptions. StoredEventHandler handlerWithErrorStatus = new StoredEventHandler(); Map<String, BuildOptions> result = transition.apply(TransitionUtil.restrict(transition, fromOptions), handlerWithErrorStatus); // We use a temporary StoredEventHandler instead of the caller's event handler because // StarlarkTransition.validate assumes no errors occurred. We need a StoredEventHandler to be // able to check that, and fail out early if there are errors. // // TODO(bazel-team): harden StarlarkTransition.validate so we can eliminate this step. // StarlarkRuleTransitionProviderTest#testAliasedBuildSetting_outputReturnMismatch shows the // effect. handlerWithErrorStatus.replayOn(eventHandler); if (handlerWithErrorStatus.hasErrors()) { throw new TransitionException("Errors encountered while applying Starlark transition"); } result = StarlarkTransition.validate(transition, buildSettingPackages, result); return result; } /** * This method allows resolution of configurations outside of a skyfunction call. * * <p>Unlike {@link #resolveConfigurations}, this doesn't expect the current context to be * evaluating dependencies of a parent target. So this method is also suitable for top-level * targets. * * <p>Resolution consists of applying the per-target transitions specified in {@code * targetsToEvaluate}. This can be used, e.g., to apply {@link * com.google.devtools.build.lib.analysis.config.transitions.TransitionFactory}s over global * top-level configurations. * * <p>Preserves the original input order (but merges duplicate nodes that might occur due to * top-level configuration transitions) . Uses original (untrimmed, pre-transition) configurations * for targets that can't be evaluated (e.g. due to loading phase errors). * * <p>This is suitable for feeding {@link * com.google.devtools.build.lib.analysis.ConfiguredTargetValue} keys: as general principle {@link * com.google.devtools.build.lib.analysis.ConfiguredTarget}s should have exactly as much * information in their configurations as they need to evaluate and no more (e.g. there's no need * for Android settings in a C++ configured target). * * @param defaultContext the original targets and starting configurations before applying rule * transitions and trimming. When actual configurations can't be evaluated, these values are * returned as defaults. See TODO below. * @param targetsToEvaluate the inputs repackaged as dependencies, including rule-specific * transitions * @param eventHandler the error event handler * @param configurationsCollector the collector which finds configurations for dependencies */ // TODO(bazel-team): error out early for targets that fail - failed configuration evaluations // should never make it through analysis (and especially not seed ConfiguredTargetValues) // TODO(gregce): merge this more with resolveConfigurations? One crucial difference is // resolveConfigurations can null-return on missing deps since it executes inside Skyfunctions. // Keep this in sync with {@link PrepareAnalysisPhaseFunction#resolveConfigurations}. public static TopLevelTargetsAndConfigsResult getConfigurationsFromExecutor( Iterable<TargetAndConfiguration> defaultContext, Multimap<BuildConfiguration, DependencyKey> targetsToEvaluate, ExtendedEventHandler eventHandler, ConfigurationsCollector configurationsCollector) throws InvalidConfigurationException, InterruptedException { Map<Label, Target> labelsToTargets = new HashMap<>(); for (TargetAndConfiguration targetAndConfig : defaultContext) { labelsToTargets.put(targetAndConfig.getLabel(), targetAndConfig.getTarget()); } // Maps <target, originalConfig> pairs to <target, finalConfig> pairs for targets that // could be successfully Skyframe-evaluated. Map<TargetAndConfiguration, TargetAndConfiguration> successfullyEvaluatedTargets = new LinkedHashMap<>(); boolean hasError = false; if (!targetsToEvaluate.isEmpty()) { for (BuildConfiguration fromConfig : targetsToEvaluate.keySet()) { ConfigurationsResult configurationsResult = configurationsCollector.getConfigurations( eventHandler, fromConfig.getOptions(), targetsToEvaluate.get(fromConfig)); hasError |= configurationsResult.hasError(); for (Map.Entry<DependencyKey, BuildConfiguration> evaluatedTarget : configurationsResult.getConfigurationMap().entries()) { Target target = labelsToTargets.get(evaluatedTarget.getKey().getLabel()); successfullyEvaluatedTargets.put( new TargetAndConfiguration(target, fromConfig), new TargetAndConfiguration(target, evaluatedTarget.getValue())); } } } LinkedHashSet<TargetAndConfiguration> result = new LinkedHashSet<>(); for (TargetAndConfiguration originalInput : defaultContext) { // If the configuration couldn't be determined (e.g. loading phase error), use the original. result.add(successfullyEvaluatedTargets.getOrDefault(originalInput, originalInput)); } return new TopLevelTargetsAndConfigsResult(result, hasError); } /** * The result of {@link #getConfigurationsFromExecutor} which also registers if an error was * recorded. */ public static class TopLevelTargetsAndConfigsResult { private final Collection<TargetAndConfiguration> configurations; private final boolean hasError; public TopLevelTargetsAndConfigsResult( Collection<TargetAndConfiguration> configurations, boolean hasError) { this.configurations = configurations; this.hasError = hasError; } public boolean hasError() { return hasError; } public Collection<TargetAndConfiguration> getTargetsAndConfigs() { return configurations; } } }
Replace ValueMissingException with null returns. In other words, treat missing Skyframe dependencies as normal control flow, unworthy of exceptions. Reference: http://www.thefinestartist.com/effective-java/57 PiperOrigin-RevId: 381941632
src/main/java/com/google/devtools/build/lib/analysis/config/ConfigurationResolver.java
Replace ValueMissingException with null returns.
Java
apache-2.0
85c25472ef74e264fe99ba5e3cc0de3cb6f87e42
0
fengshao0907/hazelcast-simulator,Danny-Hazelcast/hazelcast-stabilizer,hazelcast/hazelcast-simulator,Donnerbart/hazelcast-simulator,Donnerbart/hazelcast-simulator,pveentjer/hazelcast-simulator,gAmUssA/hazelcast-simulator,Danny-Hazelcast/hazelcast-stabilizer,jerrinot/hazelcast-stabilizer,hazelcast/hazelcast-simulator,gAmUssA/hazelcast-simulator,eminn/hazelcast-simulator,jerrinot/hazelcast-stabilizer,pveentjer/hazelcast-simulator,fengshao0907/hazelcast-simulator,eminn/hazelcast-simulator,hasancelik/hazelcast-stabilizer,hasancelik/hazelcast-stabilizer,hazelcast/hazelcast-simulator
package com.hazelcast.stabilizer.provisioner; import com.google.common.base.Predicate; import com.hazelcast.logging.ILogger; import com.hazelcast.logging.Logger; import com.hazelcast.stabilizer.Utils; import com.hazelcast.stabilizer.agent.AgentRemoteService; import com.hazelcast.stabilizer.agent.workerjvm.WorkerJvmManager; import joptsimple.OptionException; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.jclouds.ContextBuilder; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.TemplateBuilderSpec; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.scriptbuilder.statements.login.AdminAccess; import org.jclouds.sshj.config.SshjSshClientModule; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static com.hazelcast.stabilizer.Utils.appendText; import static com.hazelcast.stabilizer.Utils.fileAsLines; import static com.hazelcast.stabilizer.Utils.getVersion; import static com.hazelcast.stabilizer.Utils.secondsToHuman; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.jclouds.compute.config.ComputeServiceProperties.POLL_INITIAL_PERIOD; import static org.jclouds.compute.config.ComputeServiceProperties.POLL_MAX_PERIOD; //https://jclouds.apache.org/start/compute/ good read //https://github.com/jclouds/jclouds-examples/blob/master/compute-basics/src/main/java/org/jclouds/examples/compute/basics/MainApp.java //https://github.com/jclouds/jclouds-examples/blob/master/minecraft-compute/src/main/java/org/jclouds/examples/minecraft/NodeManager.java public class Provisioner { private final static ILogger log = Logger.getLogger(Provisioner.class.getName()); private final Properties stabilizerProperties = loadStabilizerProperties(); private final String VERSION = Utils.getVersion(); private final String CLOUD_PROVIDER = getProperty("CLOUD_PROVIDER"); private final String STABILIZER_HOME = Utils.getStablizerHome().getAbsolutePath(); private final File CONF_DIR = new File(STABILIZER_HOME, "conf"); private final File JDK_INSTALL_DIR = new File(STABILIZER_HOME, "jdk-install"); private final File agentsFile = new File("agents.txt"); //big number of threads, but they are used to offload ssh tasks. So there is no load on this machine.. private final ExecutorService executor = Executors.newFixedThreadPool(10); private final List<String> privateIps = Collections.synchronizedList(new LinkedList<String>()); public Provisioner() throws Exception { log.info("Hazelcast Stabilizer Provisioner"); log.info(format("Version: %s", getVersion())); log.info(format("STABILIZER_HOME: %s", STABILIZER_HOME)); if (!agentsFile.exists()) { agentsFile.createNewFile(); } for (String line : fileAsLines(agentsFile)) { if (line.length() > 0) { privateIps.add(line); } } } private static Properties loadStabilizerProperties() { Properties properties = new Properties(); File file = new File("stabilizer.properties"); try { FileInputStream inputStream = new FileInputStream(file); try { properties.load(inputStream); } catch (IOException e) { Utils.closeQuietly(inputStream); } } catch (IOException e) { throw new RuntimeException(e); } return properties; } void installAgent(String ip) { //first we remove the old lib files to prevent different versions of the same jar to bite us. sshQuiet(ip, format("rm -fr hazelcast-stabilizer-%s/lib", VERSION)); //then we copy the stabilizer directory scpToRemote(ip, STABILIZER_HOME, ""); String versionSpec = getProperty("HAZELCAST_VERSION_SPEC", "outofthebox"); if (!versionSpec.equals("outofthebox")) { //remove the hazelcast jars, they will be copied from the 'hazelcastJarsDir'. ssh(ip, format("rm hazelcast-stabilizer-%s/lib/hazelcast-*.jar", VERSION)); //copy the actual hazelcast jars that are going to be used by the worker. scpToRemote(ip, hazelcastJarsDir.getAbsolutePath() + "/*.jar", format("hazelcast-stabilizer-%s/lib", VERSION)); } } public void startAgents() { echoImportant("Starting %s Agents", privateIps.size()); for (String ip : privateIps) { echo("Killing Agent %s", ip); ssh(ip, "killall -9 java || true"); } for (String ip : privateIps) { echo("Starting Agent %s", ip); ssh(ip, format("nohup hazelcast-stabilizer-%s/bin/agent > agent.out 2> agent.err < /dev/null &", VERSION)); } echoImportant("Successfully started %s Agents", privateIps.size()); } void startAgent(String ip) { ssh(ip, "killall -9 java || true"); ssh(ip, format("nohup hazelcast-stabilizer-%s/bin/agent > agent.out 2> agent.err < /dev/null &", getVersion())); } void killAgents() { echoImportant("Killing %s Agents", privateIps.size()); for (String ip : privateIps) { echo("Killing Agent, %s", ip); ssh(ip, "killall -9 java || true"); } echoImportant("Successfully killed %s Agents", privateIps.size()); } public void restart() { prepareHazelcastJars(); for (String ip : privateIps) { installAgent(ip); } } public void scale(int size) throws Exception { int delta = size - privateIps.size(); if (delta == 0) { echo("Ignoring spawn machines, desired number of machines already exists"); } else if (delta < 0) { terminate(-delta); } else { scaleUp(delta); } } private int[] inboundPorts() { List<Integer> ports = new ArrayList<Integer>(); ports.add(22); //todo:the following 2 ports should not be needed ports.add(443); ports.add(80); ports.add(AgentRemoteService.PORT); ports.add(WorkerJvmManager.PORT); for (int k = 5701; k < 5901; k++) { ports.add(k); } int[] result = new int[ports.size()]; for (int k = 0; k < result.length; k++) { result[k] = ports.get(k); } return result; } private void scaleUp(int delta) throws Exception { echoImportant("Provisioning %s %s machines", delta, CLOUD_PROVIDER); echo(getProperty("MACHINE_SPEC")); long startTimeMs = System.currentTimeMillis(); String jdkFlavor = getProperty("JDK_FLAVOR"); if ("outofthebox".equals(jdkFlavor)) { log.info("Machines will use Java: Out of the Box."); } else { log.info(format("Machines will use Java: %s %s", jdkFlavor, getProperty("JDK_VERSION"))); } prepareHazelcastJars(); ComputeService compute = getComputeService(); echo("Created compute"); Template template = compute.templateBuilder() .from(TemplateBuilderSpec.parse(getProperty("MACHINE_SPEC"))) .build(); echo("Created template"); template.getOptions() .inboundPorts(inboundPorts()) .runScript(AdminAccess.standard()) .securityGroups(getProperty("SECURITY_GROUP")); echo("Creating nodes"); Set<Future> futures = new HashSet<Future>(); echo("Created machines, waiting for startup (can take a few minutes)"); for (int batch : calcBatches(delta)) { Set<? extends NodeMetadata> nodes = compute.createNodesInGroup("stabilizer-agent", batch, template); for (NodeMetadata node : nodes) { String ip = node.getPrivateAddresses().iterator().next(); echo("\t" + ip + " LAUNCHED"); appendText(ip + "\n", agentsFile); privateIps.add(ip); } for (NodeMetadata node : nodes) { Future f = executor.submit(new InstallNodeTask(node)); futures.add(f); } } for (Future f : futures) { try { f.get(); } catch (ExecutionException e) { log.severe("Failed provision", e); System.exit(1); } } long durationMs = System.currentTimeMillis() - startTimeMs; echo("Duration: " + secondsToHuman(TimeUnit.MILLISECONDS.toSeconds(durationMs))); echoImportant(format("Successfully provisioned %s %s machines", delta, getProperty("CLOUD_PROVIDER"))); } private File hazelcastJarsDir; private void prepareHazelcastJars() { File tmpDir = new File(System.getProperty("java.io.tmpdir")); hazelcastJarsDir = new File(tmpDir, "hazelcastjars-" + UUID.randomUUID().toString()); hazelcastJarsDir.mkdirs(); String versionSpec = getProperty("HAZELCAST_VERSION_SPEC", "outofthebox"); if (versionSpec.equals("outofthebox")) { log.info("Using Hazelcast version-spec: Out of the box"); } else if (versionSpec.startsWith("path=")) { String path = versionSpec.substring(5); log.info("Using Hazelcast version-spec: path=" + path); bash(format("cp %s/* %s", path, hazelcastJarsDir.getAbsolutePath())); } else if (versionSpec.equals("none")) { log.info("Using Hazelcast version-spec: none"); //we don't need to do anything } else if (versionSpec.startsWith("maven=")) { String version = versionSpec.substring(6); log.info("Using Hazelcast version-spec: maven=" + version); mavenRetrieve("hazelcast", version); mavenRetrieve("hazelcast-client", version); } else { log.severe("Unrecognized version spec:" + versionSpec); System.exit(1); } } private void mavenRetrieve(String artifact, String version) { File userhome = new File("user.home"); File repositoryDir = Utils.toFile(userhome, ".m2", "repository"); File artifactFile = Utils.toFile(repositoryDir, "com", "hazelcast", artifact, version, format("%s-%s.jar", artifact, version)); log.info("artifactFile: "+artifactFile); if (artifactFile.exists()) { log.info("Using artifact from local maven repo"); bash(format("cp %s %s",artifactFile.getAbsolutePath(),hazelcastJarsDir.getAbsolutePath())); } else { log.info("Downloading artifact from repository"); String baseUrl; if (version.endsWith("-SNAPSHOT")) { baseUrl = "https://oss.sonatype.org/content/repositories/snapshots"; } else { baseUrl = "http://repo1.maven.org/maven2"; } String url = format("%s/com/hazelcast/%s/%s/%s-%s.jar", baseUrl, artifact, version, artifact, version); bash(format("wget --no-verbose --directory-prefix=%s %s", hazelcastJarsDir.getAbsolutePath(), url)); } } private class InstallNodeTask implements Runnable { private final String ip; InstallNodeTask(NodeMetadata node) { this.ip = node.getPrivateAddresses().iterator().next(); } @Override public void run() { //install java if needed if (!"outofthebox".equals(getProperty("JDK_FLAVOR"))) { ssh(ip, "touch install-java.sh"); ssh(ip, "chmod +x install-java.sh"); scpToRemote(ip, getJavaInstallScript().getAbsolutePath(), "install-java.sh"); ssh(ip, "bash install-java.sh"); echo("\t" + ip + " JAVA INSTALLED"); } installAgent(ip); echo("\t" + ip + " STABILIZER AGENT INSTALLED"); startAgent(ip); echo("\t" + ip + " STABILIZER AGENT STARTED"); } } private int[] calcBatches(int size) { List<Integer> batches = new LinkedList<Integer>(); int batchSize = Integer.parseInt(getProperty("CLOUD_BATCH_SIZE")); while (size > 0) { int x = size >= batchSize ? batchSize : size; batches.add(x); size -= x; } int[] result = new int[batches.size()]; for (int k = 0; k < result.length; k++) { result[k] = batches.get(k); } return result; } private ComputeService getComputeService() { //http://javadocs.jclouds.cloudbees.net/org/jclouds/compute/config/ComputeServiceProperties.html Properties overrides = new Properties(); overrides.setProperty(POLL_INITIAL_PERIOD, getProperty("CLOUD_POLL_INITIAL_PERIOD")); overrides.setProperty(POLL_MAX_PERIOD, getProperty("CLOUD_POLL_MAX_PERIOD")); String credentials = getProperty("CLOUD_CREDENTIAL"); File file = new File(credentials); if (file.exists()) { credentials = Utils.fileAsText(file); } return ContextBuilder.newBuilder(getProperty("CLOUD_PROVIDER")) .overrides(overrides) .credentials(getProperty("CLOUD_IDENTITY"), credentials) .modules(asList(new Log4JLoggingModule(), new SshjSshClientModule())) .buildView(ComputeServiceContext.class) .getComputeService(); } private File getJavaInstallScript() { String flavor = getProperty("JDK_FLAVOR"); String version = getProperty("JDK_VERSION"); String script = "jdk-" + flavor + "-" + version + "-64.sh"; return new File(JDK_INSTALL_DIR, script); } public void download() { echoImportant("Download artifacts of %s machines", privateIps.size()); bash("mkdir -p workers"); for (String ip : privateIps) { echo("Downloading from %s", ip); String syncCommand = format("rsync -av -e \"ssh %s\" %s@%s:hazelcast-stabilizer-%s/workers .", getProperty("SSH_OPTIONS"), getProperty("USER"), ip, getVersion()); bash(syncCommand); } echoImportant("Finished Downloading Artifacts of %s machines", privateIps.size()); } public void clean() { echoImportant("Cleaning worker homes of %s machines", privateIps.size()); for (String ip : privateIps) { echo("Cleaning %s", ip); ssh(ip, format("rm -fr hazelcast-stabilizer-%s/workers/*", getVersion())); } echoImportant("Finished cleaning worker homes of %s machines", privateIps.size()); } public void terminate() { terminate(Integer.MAX_VALUE); } public void terminate(int count) { if (count > privateIps.size()) { count = privateIps.size(); } echoImportant(format("Terminating %s %s machines (can take some time)", count, getProperty("CLOUD_PROVIDER"))); long startMs = System.currentTimeMillis(); for (int batch : calcBatches(count)) { final List<String> terminateList = privateIps.subList(0, batch); ComputeService computeService = getComputeService(); computeService.destroyNodesMatching( new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata nodeMetadata) { for (String ip : nodeMetadata.getPrivateAddresses()) { if (terminateList.remove(ip)) { echo(format("\t%s Terminating", ip)); privateIps.remove(ip); return true; } } return false; } } ); } log.info("Updating " + agentsFile.getAbsolutePath()); writeAgentsFile(); long durationSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startMs); echo("Duration: " + secondsToHuman(durationSeconds)); echoImportant("Finished terminating %s %s machines, %s machines remaining.", count, CLOUD_PROVIDER, privateIps.size()); } private void writeAgentsFile() { String text = ""; for (String ip : privateIps) { text += ip + "\n"; } Utils.writeText(text, agentsFile); } private void bash(String command) { StringBuffer sout = new StringBuffer(); log.finest("Executing bash command: " + command); try { // create a process for the shell ProcessBuilder pb = new ProcessBuilder("bash", "-c", command); pb = pb.redirectErrorStream(true); Process shell = pb.start(); new StreamGobbler(shell.getInputStream(), sout).start(); // wait for the shell to finish and get the return code int shellExitStatus = shell.waitFor(); if (shellExitStatus != 0) { echo("Failed to execute [%s]", command); log.severe(sout.toString()); System.exit(1); } else { log.finest("Bash output: \n" + sout); } } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } } private void scpToRemote(String ip, String src, String target) { String command = format("scp -r %s %s %s@%s:%s", getProperty("SSH_OPTIONS"), src, getProperty("USER"), ip, target); bash(command); } private void ssh(String ip, String command) { String sshCommand = format("ssh %s -q %s@%s \"%s\"", getProperty("SSH_OPTIONS"), getProperty("USER"), ip, command); bash(sshCommand); } private void sshQuiet(String ip, String command) { String sshCommand = format("ssh %s -q %s@%s \"%s\" || true", getProperty("SSH_OPTIONS"), getProperty("USER"), ip, command); bash(sshCommand); } private String getProperty(String name) { return (String) stabilizerProperties.get(name); } private String getProperty(String name, String defaultValue) { String value = (String) stabilizerProperties.get(name); if (value == null) { value = defaultValue; } return value; } private void echo(String s, Object... args) { log.info(s == null ? "null" : String.format(s, args)); } private void echoImportant(String s, Object... args) { echo("=============================================================="); echo(s, args); echo("=============================================================="); } public static void main(String[] args) { try { ProvisionerCli cli = new ProvisionerCli(); OptionSet options = cli.parser.parse(args); if (options.has(cli.helpSpec)) { cli.parser.printHelpOn(System.out); System.exit(0); } Provisioner provisioner = new Provisioner(); for (OptionSpec spec : options.specs()) { if (spec.equals(cli.restartSpec)) { provisioner.restart(); provisioner.startAgents(); } else if (spec.equals(cli.killSpec)) { provisioner.killAgents(); } else if (spec.equals(cli.downloadSpec)) { provisioner.download(); } else if (spec.equals(cli.cleanSpec)) { provisioner.clean(); } else if (spec.equals(cli.terminateSpec)) { provisioner.terminate(); } else if (spec.equals(cli.scaleSpec)) { int size = options.valueOf(cli.scaleSpec); provisioner.scale(size); } } System.exit(0); } catch (OptionException e) { Utils.exitWithError(e.getMessage() + ". Use --help to get overview of the help options."); } catch (Throwable e) { log.severe(e); System.exit(1); } } }
stabilizer/src/main/java/com/hazelcast/stabilizer/provisioner/Provisioner.java
package com.hazelcast.stabilizer.provisioner; import com.google.common.base.Predicate; import com.hazelcast.logging.ILogger; import com.hazelcast.logging.Logger; import com.hazelcast.stabilizer.Utils; import com.hazelcast.stabilizer.agent.AgentRemoteService; import com.hazelcast.stabilizer.agent.workerjvm.WorkerJvmManager; import joptsimple.OptionException; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.jclouds.ContextBuilder; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.TemplateBuilderSpec; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.scriptbuilder.statements.login.AdminAccess; import org.jclouds.sshj.config.SshjSshClientModule; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static com.hazelcast.stabilizer.Utils.appendText; import static com.hazelcast.stabilizer.Utils.fileAsLines; import static com.hazelcast.stabilizer.Utils.getVersion; import static com.hazelcast.stabilizer.Utils.secondsToHuman; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.jclouds.compute.config.ComputeServiceProperties.POLL_INITIAL_PERIOD; import static org.jclouds.compute.config.ComputeServiceProperties.POLL_MAX_PERIOD; //https://jclouds.apache.org/start/compute/ good read //https://github.com/jclouds/jclouds-examples/blob/master/compute-basics/src/main/java/org/jclouds/examples/compute/basics/MainApp.java //https://github.com/jclouds/jclouds-examples/blob/master/minecraft-compute/src/main/java/org/jclouds/examples/minecraft/NodeManager.java public class Provisioner { private final static ILogger log = Logger.getLogger(Provisioner.class.getName()); private final Properties stabilizerProperties = loadStabilizerProperties(); private final String VERSION = Utils.getVersion(); private final String CLOUD_PROVIDER = getProperty("CLOUD_PROVIDER"); private final String STABILIZER_HOME = Utils.getStablizerHome().getAbsolutePath(); private final File CONF_DIR = new File(STABILIZER_HOME, "conf"); private final File JDK_INSTALL_DIR = new File(STABILIZER_HOME, "jdk-install"); private final File agentsFile = new File("agents.txt"); //big number of threads, but they are used to offload ssh tasks. So there is no load on this machine.. private final ExecutorService executor = Executors.newFixedThreadPool(10); private final List<String> privateIps = Collections.synchronizedList(new LinkedList<String>()); public Provisioner() throws Exception { log.info("Hazelcast Stabilizer Provisioner"); log.info(format("Version: %s", getVersion())); log.info(format("STABILIZER_HOME: %s", STABILIZER_HOME)); if (!agentsFile.exists()) { agentsFile.createNewFile(); } for (String line : fileAsLines(agentsFile)) { if (line.length() > 0) { privateIps.add(line); } } } private static Properties loadStabilizerProperties() { Properties properties = new Properties(); File file = new File("stabilizer.properties"); try { FileInputStream inputStream = new FileInputStream(file); try { properties.load(inputStream); } catch (IOException e) { Utils.closeQuietly(inputStream); } } catch (IOException e) { throw new RuntimeException(e); } return properties; } void installAgent(String ip) { //first we remove the old lib files to prevent different versions of the same jar to bite us. sshQuiet(ip, format("rm -fr hazelcast-stabilizer-%s/lib", VERSION)); //then we copy the stabilizer directory scpToRemote(ip, STABILIZER_HOME, ""); String versionSpec = getProperty("HAZELCAST_VERSION_SPEC", "outofthebox"); if (!versionSpec.equals("outofthebox")) { //remove the hazelcast jars, they will be copied from the 'hazelcastJarsDir'. ssh(ip, format("rm hazelcast-stabilizer-%s/lib/hazelcast-*.jar", VERSION)); //copy the actual hazelcast jars that are going to be used by the worker. scpToRemote(ip, hazelcastJarsDir.getAbsolutePath() + "/*.jar", format("hazelcast-stabilizer-%s/lib", VERSION)); } } public void startAgents() { echoImportant("Starting %s Agents", privateIps.size()); for (String ip : privateIps) { echo("Killing Agent %s", ip); ssh(ip, "killall -9 java || true"); } for (String ip : privateIps) { echo("Starting Agent %s", ip); ssh(ip, format("nohup hazelcast-stabilizer-%s/bin/agent > agent.out 2> agent.err < /dev/null &", VERSION)); } echoImportant("Successfully started %s Agents", privateIps.size()); } void startAgent(String ip) { ssh(ip, "killall -9 java || true"); ssh(ip, format("nohup hazelcast-stabilizer-%s/bin/agent > agent.out 2> agent.err < /dev/null &", getVersion())); } void killAgents() { echoImportant("Killing %s Agents", privateIps.size()); for (String ip : privateIps) { echo("Killing Agent, %s", ip); ssh(ip, "killall -9 java || true"); } echoImportant("Successfully killed %s Agents", privateIps.size()); } public void restart() { prepareHazelcastJars(); for (String ip : privateIps) { installAgent(ip); } } public void scale(int size) throws Exception { int delta = size - privateIps.size(); if (delta == 0) { echo("Ignoring spawn machines, desired number of machines already exists"); } else if (delta < 0) { terminate(-delta); } else { scaleUp(delta); } } private int[] inboundPorts() { List<Integer> ports = new ArrayList<Integer>(); ports.add(22); //todo:the following 2 ports should not be needed ports.add(443); ports.add(80); ports.add(AgentRemoteService.PORT); ports.add(WorkerJvmManager.PORT); for (int k = 5701; k < 5901; k++) { ports.add(k); } int[] result = new int[ports.size()]; for (int k = 0; k < result.length; k++) { result[k] = ports.get(k); } return result; } private void scaleUp(int delta) throws Exception { echoImportant("Provisioning %s %s machines", delta, CLOUD_PROVIDER); echo(getProperty("MACHINE_SPEC")); long startTimeMs = System.currentTimeMillis(); String jdkFlavor = getProperty("JDK_FLAVOR"); if ("outofthebox".equals(jdkFlavor)) { log.info("Machines will use Java: Out of the Box."); } else { log.info(format("Machines will use Java: %s %s", jdkFlavor, getProperty("JDK_VERSION"))); } prepareHazelcastJars(); ComputeService compute = getComputeService(); echo("Created compute"); Template template = compute.templateBuilder() .from(TemplateBuilderSpec.parse(getProperty("MACHINE_SPEC"))) .build(); echo("Created template"); template.getOptions() .inboundPorts(inboundPorts()) .runScript(AdminAccess.standard()) .securityGroups(getProperty("SECURITY_GROUP")); echo("Creating nodes"); Set<Future> futures = new HashSet<Future>(); echo("Created machines, waiting for startup (can take a few minutes)"); for (int batch : calcBatches(delta)) { Set<? extends NodeMetadata> nodes = compute.createNodesInGroup("stabilizer-agent", batch, template); for (NodeMetadata node : nodes) { String ip = node.getPrivateAddresses().iterator().next(); echo("\t" + ip + " LAUNCHED"); appendText(ip + "\n", agentsFile); privateIps.add(ip); } for (NodeMetadata node : nodes) { Future f = executor.submit(new InstallNodeTask(node)); futures.add(f); } } for (Future f : futures) { try { f.get(); } catch (ExecutionException e) { log.severe("Failed provision", e); System.exit(1); } } long durationMs = System.currentTimeMillis() - startTimeMs; echo("Duration: " + secondsToHuman(TimeUnit.MILLISECONDS.toSeconds(durationMs))); echoImportant(format("Successfully provisioned %s %s machines", delta, getProperty("CLOUD_PROVIDER"))); } private File hazelcastJarsDir; private void prepareHazelcastJars() { File tmpDir = new File(System.getProperty("java.io.tmpdir")); hazelcastJarsDir = new File(tmpDir, "hazelcastjars-" + UUID.randomUUID().toString()); hazelcastJarsDir.mkdirs(); String versionSpec = getProperty("HAZELCAST_VERSION_SPEC", "outofthebox"); if (versionSpec.equals("outofthebox")) { log.info("Using Hazelcast version-spec: Out of the box"); } else if (versionSpec.startsWith("path=")) { String path = versionSpec.substring(5); log.info("Using Hazelcast version-spec: path=" + path); bash(format("cp %s/* %s", path, hazelcastJarsDir.getAbsolutePath())); } else if (versionSpec.equals("none")) { log.info("Using Hazelcast version-spec: none"); //we don't need to do anything } else if (versionSpec.startsWith("maven=")) { String version = versionSpec.substring(6); log.info("Using Hazelcast version-spec: maven=" + version); mavenRetrieve("hazelcast", version); mavenRetrieve("hazelcast-client", version); } else { log.severe("Unrecognized version spec:" + versionSpec); System.exit(1); } } private void mavenRetrieve(String artifact, String version) { File userhome = new File("user.home"); File repositoryDir = Utils.toFile(userhome, ".m2", "repository"); File artifactFile = Utils.toFile(repositoryDir, "com", "hazelcast", artifact, version, format("%s-%s.jar", artifact, version)); if (artifactFile.exists()) { log.info("Using artifact from local maven repo"); bash(format("cp %s %s",artifactFile.getAbsolutePath(),hazelcastJarsDir.getAbsolutePath())); } else { log.info("Downloading artifact from repository"); String baseUrl; if (version.endsWith("-SNAPSHOT")) { baseUrl = "https://oss.sonatype.org/content/repositories/snapshots"; } else { baseUrl = "http://repo1.maven.org/maven2"; } String url = format("%s/com/hazelcast/%s/%s/%s-%s.jar", baseUrl, artifact, version, artifact, version); bash(format("wget --no-verbose --directory-prefix=%s %s", hazelcastJarsDir.getAbsolutePath(), url)); } } private class InstallNodeTask implements Runnable { private final String ip; InstallNodeTask(NodeMetadata node) { this.ip = node.getPrivateAddresses().iterator().next(); } @Override public void run() { //install java if needed if (!"outofthebox".equals(getProperty("JDK_FLAVOR"))) { ssh(ip, "touch install-java.sh"); ssh(ip, "chmod +x install-java.sh"); scpToRemote(ip, getJavaInstallScript().getAbsolutePath(), "install-java.sh"); ssh(ip, "bash install-java.sh"); echo("\t" + ip + " JAVA INSTALLED"); } installAgent(ip); echo("\t" + ip + " STABILIZER AGENT INSTALLED"); startAgent(ip); echo("\t" + ip + " STABILIZER AGENT STARTED"); } } private int[] calcBatches(int size) { List<Integer> batches = new LinkedList<Integer>(); int batchSize = Integer.parseInt(getProperty("CLOUD_BATCH_SIZE")); while (size > 0) { int x = size >= batchSize ? batchSize : size; batches.add(x); size -= x; } int[] result = new int[batches.size()]; for (int k = 0; k < result.length; k++) { result[k] = batches.get(k); } return result; } private ComputeService getComputeService() { //http://javadocs.jclouds.cloudbees.net/org/jclouds/compute/config/ComputeServiceProperties.html Properties overrides = new Properties(); overrides.setProperty(POLL_INITIAL_PERIOD, getProperty("CLOUD_POLL_INITIAL_PERIOD")); overrides.setProperty(POLL_MAX_PERIOD, getProperty("CLOUD_POLL_MAX_PERIOD")); String credentials = getProperty("CLOUD_CREDENTIAL"); File file = new File(credentials); if (file.exists()) { credentials = Utils.fileAsText(file); } return ContextBuilder.newBuilder(getProperty("CLOUD_PROVIDER")) .overrides(overrides) .credentials(getProperty("CLOUD_IDENTITY"), credentials) .modules(asList(new Log4JLoggingModule(), new SshjSshClientModule())) .buildView(ComputeServiceContext.class) .getComputeService(); } private File getJavaInstallScript() { String flavor = getProperty("JDK_FLAVOR"); String version = getProperty("JDK_VERSION"); String script = "jdk-" + flavor + "-" + version + "-64.sh"; return new File(JDK_INSTALL_DIR, script); } public void download() { echoImportant("Download artifacts of %s machines", privateIps.size()); bash("mkdir -p workers"); for (String ip : privateIps) { echo("Downloading from %s", ip); String syncCommand = format("rsync -av -e \"ssh %s\" %s@%s:hazelcast-stabilizer-%s/workers .", getProperty("SSH_OPTIONS"), getProperty("USER"), ip, getVersion()); bash(syncCommand); } echoImportant("Finished Downloading Artifacts of %s machines", privateIps.size()); } public void clean() { echoImportant("Cleaning worker homes of %s machines", privateIps.size()); for (String ip : privateIps) { echo("Cleaning %s", ip); ssh(ip, format("rm -fr hazelcast-stabilizer-%s/workers/*", getVersion())); } echoImportant("Finished cleaning worker homes of %s machines", privateIps.size()); } public void terminate() { terminate(Integer.MAX_VALUE); } public void terminate(int count) { if (count > privateIps.size()) { count = privateIps.size(); } echoImportant(format("Terminating %s %s machines (can take some time)", count, getProperty("CLOUD_PROVIDER"))); long startMs = System.currentTimeMillis(); for (int batch : calcBatches(count)) { final List<String> terminateList = privateIps.subList(0, batch); ComputeService computeService = getComputeService(); computeService.destroyNodesMatching( new Predicate<NodeMetadata>() { @Override public boolean apply(NodeMetadata nodeMetadata) { for (String ip : nodeMetadata.getPrivateAddresses()) { if (terminateList.remove(ip)) { echo(format("\t%s Terminating", ip)); privateIps.remove(ip); return true; } } return false; } } ); } log.info("Updating " + agentsFile.getAbsolutePath()); writeAgentsFile(); long durationSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startMs); echo("Duration: " + secondsToHuman(durationSeconds)); echoImportant("Finished terminating %s %s machines, %s machines remaining.", count, CLOUD_PROVIDER, privateIps.size()); } private void writeAgentsFile() { String text = ""; for (String ip : privateIps) { text += ip + "\n"; } Utils.writeText(text, agentsFile); } private void bash(String command) { StringBuffer sout = new StringBuffer(); log.finest("Executing bash command: " + command); try { // create a process for the shell ProcessBuilder pb = new ProcessBuilder("bash", "-c", command); pb = pb.redirectErrorStream(true); Process shell = pb.start(); new StreamGobbler(shell.getInputStream(), sout).start(); // wait for the shell to finish and get the return code int shellExitStatus = shell.waitFor(); if (shellExitStatus != 0) { echo("Failed to execute [%s]", command); log.severe(sout.toString()); System.exit(1); } else { log.finest("Bash output: \n" + sout); } } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } } private void scpToRemote(String ip, String src, String target) { String command = format("scp -r %s %s %s@%s:%s", getProperty("SSH_OPTIONS"), src, getProperty("USER"), ip, target); bash(command); } private void ssh(String ip, String command) { String sshCommand = format("ssh %s -q %s@%s \"%s\"", getProperty("SSH_OPTIONS"), getProperty("USER"), ip, command); bash(sshCommand); } private void sshQuiet(String ip, String command) { String sshCommand = format("ssh %s -q %s@%s \"%s\" || true", getProperty("SSH_OPTIONS"), getProperty("USER"), ip, command); bash(sshCommand); } private String getProperty(String name) { return (String) stabilizerProperties.get(name); } private String getProperty(String name, String defaultValue) { String value = (String) stabilizerProperties.get(name); if (value == null) { value = defaultValue; } return value; } private void echo(String s, Object... args) { log.info(s == null ? "null" : String.format(s, args)); } private void echoImportant(String s, Object... args) { echo("=============================================================="); echo(s, args); echo("=============================================================="); } public static void main(String[] args) { try { ProvisionerCli cli = new ProvisionerCli(); OptionSet options = cli.parser.parse(args); if (options.has(cli.helpSpec)) { cli.parser.printHelpOn(System.out); System.exit(0); } Provisioner provisioner = new Provisioner(); for (OptionSpec spec : options.specs()) { if (spec.equals(cli.restartSpec)) { provisioner.restart(); provisioner.startAgents(); } else if (spec.equals(cli.killSpec)) { provisioner.killAgents(); } else if (spec.equals(cli.downloadSpec)) { provisioner.download(); } else if (spec.equals(cli.cleanSpec)) { provisioner.clean(); } else if (spec.equals(cli.terminateSpec)) { provisioner.terminate(); } else if (spec.equals(cli.scaleSpec)) { int size = options.valueOf(cli.scaleSpec); provisioner.scale(size); } } System.exit(0); } catch (OptionException e) { Utils.exitWithError(e.getMessage() + ". Use --help to get overview of the help options."); } catch (Throwable e) { log.severe(e); System.exit(1); } } }
minor tweak
stabilizer/src/main/java/com/hazelcast/stabilizer/provisioner/Provisioner.java
minor tweak
Java
apache-2.0
0c422dc6888bbaa43ebfc4198d9c2974dea32ff0
0
naren01/wordcram,cmballard07/wordcram,allendaicool/wordcram,allendaicool/wordcram,naren01/wordcram,tectronics/wordcram,cmballard07/wordcram,tectronics/wordcram,allendaicool/wordcram,tectronics/wordcram,cmballard07/wordcram,naren01/wordcram,cmballard07/wordcram,naren01/wordcram
package wordcram; class RenderOptions { int maxAttemptsForPlacement = -1; // default: based on Word weight int maxNumberOfWordsToDraw = -1; // default: unlimited int minShapeSize = 7; boolean printWhenSkippingWords = false; }
src/wordcram/RenderOptions.java
package wordcram; class RenderOptions { int maxAttemptsForPlacement = -1; // default: based on Word weight int maxNumberOfWordsToDraw = -1; // default: unlimited int minShapeSize = 7; boolean printWhenSkippingWords = false; // TODO add (& use) remaining RenderOptions // int boundingBoxSwell; // default: 0 // int minBoundingBox; // default: 2 }
removed TODOs
src/wordcram/RenderOptions.java
removed TODOs
Java
apache-2.0
e3ef7c1bd05b665c1341c1f00ed9a15636d0f040
0
cuba-platform/cuba,cuba-platform/cuba,cuba-platform/cuba
/* * Copyright (c) 2008-2016 Haulmont. * * 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.haulmont.cuba.gui.app.security.role.browse; import com.google.common.io.Files; import com.haulmont.bali.util.ParamsMap; import com.haulmont.cuba.core.app.importexport.CollectionImportPolicy; import com.haulmont.cuba.core.app.importexport.EntityImportExportService; import com.haulmont.cuba.core.app.importexport.EntityImportView; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.gui.UiComponents; import com.haulmont.cuba.gui.WindowManager.OpenType; import com.haulmont.cuba.gui.WindowParam; import com.haulmont.cuba.gui.WindowParams; import com.haulmont.cuba.gui.components.*; import com.haulmont.cuba.gui.components.actions.ItemTrackingAction; import com.haulmont.cuba.gui.components.actions.RemoveAction; import com.haulmont.cuba.gui.data.CollectionDatasource; import com.haulmont.cuba.gui.export.ByteArrayDataProvider; import com.haulmont.cuba.gui.export.ExportDisplay; import com.haulmont.cuba.gui.export.ExportFormat; import com.haulmont.cuba.gui.upload.FileUploadingAPI; import com.haulmont.cuba.security.app.UserManagementService; import com.haulmont.cuba.security.entity.*; import com.haulmont.cuba.security.role.RolesService; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Named; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.*; public class RoleBrowser extends AbstractLookup { protected static final String DEFAULT_ROLE_PROPERTY = "defaultRole"; private final Logger log = LoggerFactory.getLogger(RoleBrowser.class); @WindowParam protected String securityScope; @Inject protected UserManagementService userManagementService; @Inject protected UiComponents uiComponents; @Inject protected Security security; @Inject protected Metadata metadata; @Inject protected DataManager dataManager; @Inject protected ViewRepository viewRepository; @Inject protected FileUploadingAPI fileUploadingAPI; @Inject protected ExportDisplay exportDisplay; @Inject protected EntityImportExportService entityImportExportService; @Inject protected RolesService rolesService; @Inject protected CollectionDatasource<Role, UUID> rolesDs; @Inject protected FileUploadField importRolesUpload; @Inject protected PopupButton exportBtn; @Inject protected Button createBtn; @Inject protected Button removeBtn; @Inject protected Button copyBtn; @Inject protected TextField<String> nameField; @Inject protected TextField<String> locNameField; @Inject protected TextField<String> descriptionField; @Inject protected Table<Role> rolesTable; @Named("rolesTable.remove") protected RemoveAction removeRolesAction; @Override public void init(Map<String, Object> params) { super.init(params); removeRolesAction.setBeforeActionPerformedHandler(() -> { Set<Role> selectedRoles = rolesTable.getSelected(); for (Role role : selectedRoles) { if (role.isPredefined()) { showNotification(getMessage("predefinedRoleDeletion")); return false; } } return true; }); Action copyRoles = new ItemTrackingAction("copy") .withCaption(getMessage("actions.Copy")) .withHandler(event -> { if (rolesTable.getSingleSelected() != null && rolesTable.getSingleSelected().isPredefined()) { userManagementService.copyRole(rolesTable.getSingleSelected().getName()); } else { userManagementService.copyRole(rolesTable.getSingleSelected().getId()); } rolesDs.refresh(); }); boolean hasPermissionsToCreateRole = security.isEntityOpPermitted(Role.class, EntityOp.CREATE); copyRoles.setEnabled(hasPermissionsToCreateRole && rolesService.isRoleStorageMixedMode()); rolesTable.addAction(copyRoles); Action assignToUsersAction = new ItemTrackingAction(rolesTable, "assignToUsers") .withCaption(getMessage("assignToUsers")) .withHandler(event -> { Set<Role> selected = rolesTable.getSelected(); if (selected.isEmpty()) { showNotification(getMessage("selectRole.msg"), NotificationType.HUMANIZED); return; } Role role = selected.iterator().next(); Map<String, Object> userLookupParams = new HashMap<>(); WindowParams.MULTI_SELECT.set(userLookupParams, true); openLookup(User.class, items -> { assignRoleUsers(role, items); }, OpenType.THIS_TAB, userLookupParams); }); rolesTable.addAction(assignToUsersAction); boolean hasPermissionsToCreateUserRole = security.isEntityOpPermitted(UserRole.class, EntityOp.CREATE); Action copy = rolesTable.getAction("assignToUsers"); if (copy != null) { copy.setEnabled(hasPermissionsToCreateUserRole); } String windowOpener = (String) params.get("param$windowOpener"); if ("sec$User.edit".equals(windowOpener)) { rolesTable.setMultiSelect(true); } if (security.isEntityAttrReadPermitted(rolesDs.getMetaClass(), "defaultRole")) { rolesTable.addGeneratedColumn("defaultRole", entity -> { CheckBox checkBox = uiComponents.create(CheckBox.NAME); checkBox.setValue(Boolean.TRUE.equals(entity.getDefaultRole())); checkBox.setEditable(!entity.isPredefined()); checkBox.addValueChangeListener(e -> entity.setDefaultRole(e.getValue())); return checkBox; }); } rolesDs.addItemPropertyChangeListener(e -> { if (DEFAULT_ROLE_PROPERTY.equals(e.getProperty())) { Role role = e.getItem(); if (!role.isPredefined()) { Role reloadedRole = dataManager.reload(e.getItem(), View.LOCAL); reloadedRole.setDefaultRole(e.getItem().getDefaultRole()); rolesDs.updateItem(reloadedRole); rolesDs.modifyItem(reloadedRole); rolesDs.commit(); } } }); importRolesUpload.addFileUploadSucceedListener(event -> importRoles() ); importRolesUpload.setCaption(null); importRolesUpload.setUploadButtonCaption(null); if (!rolesService.isRoleStorageMixedMode()) { createBtn.setVisible(false); removeBtn.setVisible(false); copyBtn.setVisible(false); exportBtn.setVisible(false); importRolesUpload.setVisible(false); } nameField.addValueChangeListener(e -> applyFilter()); locNameField.addValueChangeListener(e -> applyFilter()); descriptionField.addValueChangeListener(e -> applyFilter()); } protected void applyFilter() { rolesDs.refresh(ParamsMap.of( "name", nameField.getValue(), "locName", locNameField.getValue(), "description", descriptionField.getValue() )); } protected void importRoles() { File file = fileUploadingAPI.getFile(importRolesUpload.getFileId()); if (file == null) { String errorMsg = String.format("Entities import upload error. File with id %s not found", importRolesUpload.getFileId()); throw new RuntimeException(errorMsg); } byte[] fileBytes; try (InputStream is = new FileInputStream(file)) { fileBytes = IOUtils.toByteArray(is); } catch (IOException e) { throw new RuntimeException("Unable to import file", e); } try { Collection<Entity> importedEntities; deleteSoftDeletedEntities(); if ("json".equals(Files.getFileExtension(importRolesUpload.getFileName()))) { String jsonContent = new String(fileBytes, StandardCharsets.UTF_8); importedEntities = entityImportExportService.importEntitiesFromJSON(jsonContent, createRolesImportView()); } else { importedEntities = entityImportExportService.importEntitiesFromZIP(fileBytes, createRolesImportView()); } long importedRolesCount = importedEntities.stream() .filter(entity -> entity instanceof Role) .count(); showNotification(importedRolesCount + " roles imported", NotificationType.HUMANIZED); rolesDs.refresh(); } catch (Exception e) { showNotification(formatMessage("importError", e.getMessage()), NotificationType.ERROR); } try { fileUploadingAPI.deleteFile(importRolesUpload.getFileId()); } catch (FileStorageException e) { log.error("Unable to delete temp file", e); } } /** * Physically remove soft-deleted Roles and Permissions from the database before the import to avoid unique constraint violations. * Fix of the https://github.com/cuba-platform/cuba/issues/2288 */ protected void deleteSoftDeletedEntities() { List<Role> deletedRoles = dataManager.load(Role.class) .softDeletion(false) .query("select p from sec$Role p where p.deleteTs is not null") .list(); List<Permission> deletedPermissions = dataManager.load(Permission.class) .softDeletion(false) .query("select p from sec$Permission p where p.deleteTs is not null") .list(); List<Entity> entitiesToRemove = new ArrayList<>(); entitiesToRemove.addAll(deletedRoles); entitiesToRemove.addAll(deletedPermissions); CommitContext ctx = new CommitContext(); ctx.setSoftDeletion(false); ctx.setRemoveInstances(entitiesToRemove); dataManager.commit(ctx); if (!deletedPermissions.isEmpty() || !deletedRoles.isEmpty()) { log.debug("Soft deleted entities removed: {} roles and {} permissions", deletedRoles.size(), deletedPermissions.size()); } } protected void assignRoleUsers(Role role, Collection<User> items) { if (items == null) return; List<Entity> toCommit = new ArrayList<>(); for (User user : items) { LoadContext<UserRole> ctx = LoadContext.create(UserRole.class) .setView("user.edit") .setQuery(new LoadContext.Query("select ur from sec$UserRole ur where ur.user.id = :userId") .setParameter("userId", user.getId()) ); List<UserRole> userRoles = dataManager.loadList(ctx); boolean roleExist = false; for (UserRole userRole : userRoles) { if ((!role.isPredefined() && role.equals(userRole.getRole()) || (role.isPredefined() && role.getName().equals(userRole.getRoleName())))) { roleExist = true; break; } } if (!roleExist) { UserRole ur = metadata.create(UserRole.class); ur.setUser(user); if (role.isPredefined()) { ur.setRoleName(role.getName()); } else { ur.setRole(role); } toCommit.add(ur); } } if (!toCommit.isEmpty()) { dataManager.commit(new CommitContext(toCommit)); } showNotification(getMessage("rolesAssigned.msg")); } protected EntityImportView createRolesImportView() { return new EntityImportView(Role.class) .addLocalProperties() .addOneToManyProperty("permissions", new EntityImportView(Permission.class).addLocalProperties(), CollectionImportPolicy.REMOVE_ABSENT_ITEMS); } public void exportZIP() { export(ExportFormat.ZIP); } public void exportJSON() { export(ExportFormat.JSON); } protected void export(ExportFormat exportFormat) { Collection<Role> selected = rolesTable.getSelected(); if (selected.isEmpty() && rolesTable.getItems() != null) { selected = rolesTable.getItems().getItems(); } View view = viewRepository.getView(Role.class, "role.export"); if (view == null) { throw new DevelopmentException("View 'role.export' for sec$Role was not found"); } try { if (exportFormat == ExportFormat.ZIP) { byte[] data = entityImportExportService.exportEntitiesToZIP(selected, view); exportDisplay.show(new ByteArrayDataProvider(data), "Roles", ExportFormat.ZIP); } else if (exportFormat == ExportFormat.JSON) { byte[] data = entityImportExportService.exportEntitiesToJSON(selected, view) .getBytes(StandardCharsets.UTF_8); exportDisplay.show(new ByteArrayDataProvider(data), "Roles", ExportFormat.JSON); } } catch (Exception e) { showNotification(getMessage("exportFailed"), e.getMessage(), NotificationType.ERROR); log.error("Roles export failed", e); } } }
modules/gui/src/com/haulmont/cuba/gui/app/security/role/browse/RoleBrowser.java
/* * Copyright (c) 2008-2016 Haulmont. * * 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.haulmont.cuba.gui.app.security.role.browse; import com.google.common.io.Files; import com.haulmont.bali.util.ParamsMap; import com.haulmont.cuba.core.app.importexport.CollectionImportPolicy; import com.haulmont.cuba.core.app.importexport.EntityImportExportService; import com.haulmont.cuba.core.app.importexport.EntityImportView; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.gui.UiComponents; import com.haulmont.cuba.gui.WindowManager.OpenType; import com.haulmont.cuba.gui.WindowParam; import com.haulmont.cuba.gui.WindowParams; import com.haulmont.cuba.gui.components.*; import com.haulmont.cuba.gui.components.actions.ItemTrackingAction; import com.haulmont.cuba.gui.components.actions.RemoveAction; import com.haulmont.cuba.gui.data.CollectionDatasource; import com.haulmont.cuba.gui.export.ByteArrayDataProvider; import com.haulmont.cuba.gui.export.ExportDisplay; import com.haulmont.cuba.gui.export.ExportFormat; import com.haulmont.cuba.gui.upload.FileUploadingAPI; import com.haulmont.cuba.security.app.UserManagementService; import com.haulmont.cuba.security.entity.*; import com.haulmont.cuba.security.role.RolesService; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Named; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.*; public class RoleBrowser extends AbstractLookup { protected static final String DEFAULT_ROLE_PROPERTY = "defaultRole"; private final Logger log = LoggerFactory.getLogger(RoleBrowser.class); @WindowParam protected String securityScope; @Inject protected UserManagementService userManagementService; @Inject protected UiComponents uiComponents; @Inject protected Security security; @Inject protected Metadata metadata; @Inject protected DataManager dataManager; @Inject protected ViewRepository viewRepository; @Inject protected FileUploadingAPI fileUploadingAPI; @Inject protected ExportDisplay exportDisplay; @Inject protected EntityImportExportService entityImportExportService; @Inject protected RolesService rolesService; @Inject protected CollectionDatasource<Role, UUID> rolesDs; @Inject protected FileUploadField importRolesUpload; @Inject protected PopupButton exportBtn; @Inject protected Button createBtn; @Inject protected Button removeBtn; @Inject protected Button copyBtn; @Inject protected TextField<String> nameField; @Inject protected TextField<String> locNameField; @Inject protected TextField<String> descriptionField; @Inject protected Table<Role> rolesTable; @Named("rolesTable.remove") protected RemoveAction removeRolesAction; @Override public void init(Map<String, Object> params) { super.init(params); removeRolesAction.setBeforeActionPerformedHandler(() -> { Set<Role> selectedRoles = rolesTable.getSelected(); for (Role role : selectedRoles) { if (role.isPredefined()) { showNotification(getMessage("predefinedRoleDeletion")); return false; } } return true; }); Action copyRoles = new ItemTrackingAction("copy") .withCaption(getMessage("actions.Copy")) .withHandler(event -> { if (rolesTable.getSingleSelected() != null && rolesTable.getSingleSelected().isPredefined()) { userManagementService.copyRole(rolesTable.getSingleSelected().getName()); } else { userManagementService.copyRole(rolesTable.getSingleSelected().getId()); } rolesDs.refresh(); }); boolean hasPermissionsToCreateRole = security.isEntityOpPermitted(Role.class, EntityOp.CREATE); copyRoles.setEnabled(hasPermissionsToCreateRole && rolesService.isRoleStorageMixedMode()); rolesTable.addAction(copyRoles); Action assignToUsersAction = new ItemTrackingAction(rolesTable, "assignToUsers") .withCaption(getMessage("assignToUsers")) .withHandler(event -> { Set<Role> selected = rolesTable.getSelected(); if (selected.isEmpty()) { showNotification(getMessage("selectRole.msg"), NotificationType.HUMANIZED); return; } Role role = selected.iterator().next(); Map<String, Object> userLookupParams = new HashMap<>(); WindowParams.MULTI_SELECT.set(userLookupParams, true); openLookup(User.class, items -> { assignRoleUsers(role, items); }, OpenType.THIS_TAB, userLookupParams); }); rolesTable.addAction(assignToUsersAction); boolean hasPermissionsToCreateUserRole = security.isEntityOpPermitted(UserRole.class, EntityOp.CREATE); Action copy = rolesTable.getAction("assignToUsers"); if (copy != null) { copy.setEnabled(hasPermissionsToCreateUserRole); } String windowOpener = (String) params.get("param$windowOpener"); if ("sec$User.edit".equals(windowOpener)) { rolesTable.setMultiSelect(true); } rolesTable.addGeneratedColumn("defaultRole", entity -> { CheckBox checkBox = uiComponents.create(CheckBox.NAME); checkBox.setValue(Boolean.TRUE.equals(entity.getDefaultRole())); checkBox.setEditable(!entity.isPredefined()); checkBox.addValueChangeListener(e -> entity.setDefaultRole(e.getValue())); return checkBox; }); rolesDs.addItemPropertyChangeListener(e -> { if (DEFAULT_ROLE_PROPERTY.equals(e.getProperty())) { Role role = e.getItem(); if (!role.isPredefined()) { Role reloadedRole = dataManager.reload(e.getItem(), View.LOCAL); reloadedRole.setDefaultRole(e.getItem().getDefaultRole()); rolesDs.updateItem(reloadedRole); rolesDs.modifyItem(reloadedRole); rolesDs.commit(); } } }); importRolesUpload.addFileUploadSucceedListener(event -> importRoles() ); importRolesUpload.setCaption(null); importRolesUpload.setUploadButtonCaption(null); if (!rolesService.isRoleStorageMixedMode()) { createBtn.setVisible(false); removeBtn.setVisible(false); copyBtn.setVisible(false); exportBtn.setVisible(false); importRolesUpload.setVisible(false); } nameField.addValueChangeListener(e -> applyFilter()); locNameField.addValueChangeListener(e -> applyFilter()); descriptionField.addValueChangeListener(e -> applyFilter()); } protected void applyFilter() { rolesDs.refresh(ParamsMap.of( "name", nameField.getValue(), "locName", locNameField.getValue(), "description", descriptionField.getValue() )); } protected void importRoles() { File file = fileUploadingAPI.getFile(importRolesUpload.getFileId()); if (file == null) { String errorMsg = String.format("Entities import upload error. File with id %s not found", importRolesUpload.getFileId()); throw new RuntimeException(errorMsg); } byte[] fileBytes; try (InputStream is = new FileInputStream(file)) { fileBytes = IOUtils.toByteArray(is); } catch (IOException e) { throw new RuntimeException("Unable to import file", e); } try { Collection<Entity> importedEntities; deleteSoftDeletedEntities(); if ("json".equals(Files.getFileExtension(importRolesUpload.getFileName()))) { String jsonContent = new String(fileBytes, StandardCharsets.UTF_8); importedEntities = entityImportExportService.importEntitiesFromJSON(jsonContent, createRolesImportView()); } else { importedEntities = entityImportExportService.importEntitiesFromZIP(fileBytes, createRolesImportView()); } long importedRolesCount = importedEntities.stream() .filter(entity -> entity instanceof Role) .count(); showNotification(importedRolesCount + " roles imported", NotificationType.HUMANIZED); rolesDs.refresh(); } catch (Exception e) { showNotification(formatMessage("importError", e.getMessage()), NotificationType.ERROR); } try { fileUploadingAPI.deleteFile(importRolesUpload.getFileId()); } catch (FileStorageException e) { log.error("Unable to delete temp file", e); } } /** * Physically remove soft-deleted Roles and Permissions from the database before the import to avoid unique constraint violations. * Fix of the https://github.com/cuba-platform/cuba/issues/2288 */ protected void deleteSoftDeletedEntities() { List<Role> deletedRoles = dataManager.load(Role.class) .softDeletion(false) .query("select p from sec$Role p where p.deleteTs is not null") .list(); List<Permission> deletedPermissions = dataManager.load(Permission.class) .softDeletion(false) .query("select p from sec$Permission p where p.deleteTs is not null") .list(); List<Entity> entitiesToRemove = new ArrayList<>(); entitiesToRemove.addAll(deletedRoles); entitiesToRemove.addAll(deletedPermissions); CommitContext ctx = new CommitContext(); ctx.setSoftDeletion(false); ctx.setRemoveInstances(entitiesToRemove); dataManager.commit(ctx); if (!deletedPermissions.isEmpty() || !deletedRoles.isEmpty()) { log.debug("Soft deleted entities removed: {} roles and {} permissions", deletedRoles.size(), deletedPermissions.size()); } } protected void assignRoleUsers(Role role, Collection<User> items) { if (items == null) return; List<Entity> toCommit = new ArrayList<>(); for (User user : items) { LoadContext<UserRole> ctx = LoadContext.create(UserRole.class) .setView("user.edit") .setQuery(new LoadContext.Query("select ur from sec$UserRole ur where ur.user.id = :userId") .setParameter("userId", user.getId()) ); List<UserRole> userRoles = dataManager.loadList(ctx); boolean roleExist = false; for (UserRole userRole : userRoles) { if ((!role.isPredefined() && role.equals(userRole.getRole()) || (role.isPredefined() && role.getName().equals(userRole.getRoleName())))) { roleExist = true; break; } } if (!roleExist) { UserRole ur = metadata.create(UserRole.class); ur.setUser(user); if (role.isPredefined()) { ur.setRoleName(role.getName()); } else { ur.setRole(role); } toCommit.add(ur); } } if (!toCommit.isEmpty()) { dataManager.commit(new CommitContext(toCommit)); } showNotification(getMessage("rolesAssigned.msg")); } protected EntityImportView createRolesImportView() { return new EntityImportView(Role.class) .addLocalProperties() .addOneToManyProperty("permissions", new EntityImportView(Permission.class).addLocalProperties(), CollectionImportPolicy.REMOVE_ABSENT_ITEMS); } public void exportZIP() { export(ExportFormat.ZIP); } public void exportJSON() { export(ExportFormat.JSON); } protected void export(ExportFormat exportFormat) { Collection<Role> selected = rolesTable.getSelected(); if (selected.isEmpty() && rolesTable.getItems() != null) { selected = rolesTable.getItems().getItems(); } View view = viewRepository.getView(Role.class, "role.export"); if (view == null) { throw new DevelopmentException("View 'role.export' for sec$Role was not found"); } try { if (exportFormat == ExportFormat.ZIP) { byte[] data = entityImportExportService.exportEntitiesToZIP(selected, view); exportDisplay.show(new ByteArrayDataProvider(data), "Roles", ExportFormat.ZIP); } else if (exportFormat == ExportFormat.JSON) { byte[] data = entityImportExportService.exportEntitiesToJSON(selected, view) .getBytes(StandardCharsets.UTF_8); exportDisplay.show(new ByteArrayDataProvider(data), "Roles", ExportFormat.JSON); } } catch (Exception e) { showNotification(getMessage("exportFailed"), e.getMessage(), NotificationType.ERROR); log.error("Roles export failed", e); } } }
Generated columns are not hidden by the new security mechanism cuba-platform/cuba#2979
modules/gui/src/com/haulmont/cuba/gui/app/security/role/browse/RoleBrowser.java
Generated columns are not hidden by the new security mechanism cuba-platform/cuba#2979
Java
apache-2.0
e4cd8fb1d1232c5114abbd763db8fca656736eb6
0
phon-ca/phon-praat-plugin,phon-ca/phon-praat-plugin
package ca.phon.plugins.praat.export; import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import ca.phon.ipa.IPAElement; import ca.phon.ipa.IPATranscript; import ca.phon.media.util.MediaLocator; import ca.phon.orthography.OrthoElement; import ca.phon.plugins.praat.Segmentation; import ca.phon.plugins.praat.TextGridManager; import ca.phon.plugins.praat.script.PraatScript; import ca.phon.plugins.praat.script.PraatScriptContext; import ca.phon.project.Project; import ca.phon.session.Group; import ca.phon.session.MediaSegment; import ca.phon.session.MediaUnit; import ca.phon.session.Record; import ca.phon.session.RecordFilter; import ca.phon.session.Session; import ca.phon.session.SystemTierType; import ca.phon.session.Tier; import ca.phon.syllable.SyllableConstituentType; import ca.phon.textgrid.TextGrid; import ca.phon.textgrid.TextGridInterval; import ca.phon.textgrid.TextGridTier; import ca.phon.textgrid.TextGridTierType; import ca.phon.textgrid.TextGridWriter; /** * Utility methods for exporting Phon tier data into * TextGrids * */ public class TextGridExporter { private static final Logger LOGGER = Logger .getLogger(TextGridExporter.class.getName()); /** Default hash length in ms */ public final static float MARKER_LENGTH = 0.1f; /** Default marker interval/point text */ public final static String MARKER_TEXT = "#"; /** Default space length in ms */ public final static float SPACER_LENGTH = 0.01f; public final static String SPACER_TEXT = " "; /** * Location of text grid export defaults */ private final static String EXPORT_DEFAULTS = "__res/plugin_data/textgrid/exportdefaults.xml"; /** * Export phon tier to textgrid * * @param utt * @param textgrid * @param entry */ public void addTierToTextGrid(Record utt, TextGrid textgrid, TextGridExportEntry entry) { addTierToTextGrid(utt, entry.getPhonTier(), entry.getExportType(), textgrid, entry.getTextGridTier()); } /** * Export the specified tier from the given Phon record * into the given text grid with specified name. * * @param record * @param tier * @param type * @param textgrid * @param tgName */ public void addTierToTextGrid(Record record, String tier, Segmentation type, TextGrid textgrid, String tgName) { // create the new textgrid tier final TextGridTier tgTier = new TextGridTier(tgName, TextGridTierType.INTERVAL); textgrid.addTier(tgTier); // check if we a processing a built-in tier final SystemTierType systemTier = SystemTierType.tierFromString(tier); // calculate some values for interval times final int numHashes = record.numberOfGroups() + 1; final float totalTime = textgrid.getMax() - textgrid.getMin(); final float hashLength = MARKER_LENGTH * numHashes; final float dataLength = totalTime - hashLength; final float groupLength = dataLength / record.numberOfGroups(); // if the exportType is TIER, we create a 3-interval tier // this takes care of all flat tiers if(type == Segmentation.TIER) { setupThreeIntervalTier(textgrid, tgTier, record.getTier(tier, String.class).toString()); } else { float currentStart = textgrid.getMin(); float dataEnd = textgrid.getMax() - MARKER_LENGTH; // final List<IWord> words = utt.getWords(); for(int i = 0; i < record.numberOfGroups(); i++) { final Group group = record.getGroup(i); // add group marker final TextGridInterval marker = new TextGridInterval(MARKER_TEXT, currentStart, currentStart + MARKER_LENGTH); tgTier.addInterval(marker); currentStart += MARKER_LENGTH; // final IWord word = words.get(i); final float groupStart = currentStart; final float groupEnd = (i == record.numberOfGroups() - 1 ? dataEnd : groupStart + groupLength); if(type == Segmentation.GROUP) { String data = ""; if(systemTier != null) { if(systemTier == SystemTierType.Orthography) { data = group.getOrthography().toString(); } else if(systemTier == SystemTierType.IPATarget) { data = group.getIPATarget().toString(); } else if(systemTier == SystemTierType.IPAActual) { data = group.getIPAActual().toString(); } } else { data = group.getTier(tier).toString(); } addGroup(tgTier, data, currentStart, groupEnd); currentStart = groupEnd; } else if(type == Segmentation.WORD) { String data = ""; if(systemTier != null) { if(systemTier == SystemTierType.Orthography) { data = ""; for(int wIdx = 0; wIdx < group.getAlignedWordCount(); wIdx++) { final String orthoWord = group.getAlignedWord(wIdx).getOrthography().toString(); data += (data.length() > 0 ? " " : "") + orthoWord; } } else if(systemTier == SystemTierType.IPATarget) { data = group.getIPATarget().toString(); } else if(systemTier == SystemTierType.IPAActual) { data = group.getIPAActual().toString(); } } else { data = group.getTier(tier, String.class); } addWords(tgTier, data, currentStart, groupEnd); currentStart = groupEnd; } else if(type == Segmentation.SYLLABLE) { if(systemTier == SystemTierType.IPATarget || systemTier == SystemTierType.IPAActual) { addSyllables(tgTier, systemTier == SystemTierType.IPATarget ? group.getIPATarget() : group.getIPAActual(), currentStart, groupEnd); currentStart = groupEnd; } } else if(type == Segmentation.PHONE) { if(systemTier == SystemTierType.IPATarget || systemTier == SystemTierType.IPAActual) { addPhones(tgTier, systemTier == SystemTierType.IPATarget ? group.getIPATarget() : group.getIPAActual(), currentStart, groupEnd); currentStart = groupEnd; } } } // add final marker final TextGridInterval marker = new TextGridInterval(MARKER_TEXT, dataEnd, textgrid.getMax()); tgTier.addInterval(marker); } } private void addGroup(TextGridTier tier, String groupData, float start, float end) { final TextGridInterval interval = new TextGridInterval(groupData, start, end); tier.addInterval(interval); } private void addWords(TextGridTier tier, String groupData, float start, float end) { final String[] words = groupData.split("\\p{Space}"); final float wordLength = (end - start) / words.length; float currentStart = start; for(int i = 0; i < words.length; i++) { String word = words[i]; final TextGridInterval interval = new TextGridInterval(word, currentStart, (i == words.length - 1 ? end : currentStart + wordLength)); currentStart += wordLength; tier.addInterval(interval); } } private void addSyllables(TextGridTier tier, IPATranscript ipaGroup, float start, float end) { final List<IPATranscript> ipaWords = ipaGroup.words(); // calculate length of each word final float dataLength = (end - start); final float wordLength = dataLength / ipaWords.size(); // add intervals to tier float currentStart = start; for(int i = 0; i < ipaWords.size(); i++) { if(i > 0) { // add space to previous interval final TextGridInterval lastInterval = (tier.getNumberOfIntervals() > 0 ? tier.getIntervalAt(tier.getNumberOfIntervals()-1) : null); if(lastInterval != null) { lastInterval.setLabel(lastInterval.getLabel() + SPACER_TEXT); } } final IPATranscript word = ipaWords.get(i); final List<IPATranscript> sylls = word.syllables(); final float wordStart = currentStart; final float wordEnd = (i == ipaWords.size() - 1 ? end : wordStart + wordLength); final float syllLength = wordLength / sylls.size(); for(int j = 0; j < sylls.size(); j++) { final IPATranscript syll = sylls.get(j); float intEnd = (j == sylls.size() - 1 ? wordEnd : currentStart + syllLength); final TextGridInterval interval = new TextGridInterval(syll.toString(), currentStart, intEnd); tier.addInterval(interval); currentStart = intEnd; } } } private void addPhones(TextGridTier tier, IPATranscript ipaGroup, float start, float end) { final List<IPATranscript> ipaWords = ipaGroup.words(); // calculate length of each word final float dataLength = (end - start); final float wordLength = dataLength / ipaWords.size(); // add intervals to tier float currentStart = start; for(int i = 0; i < ipaWords.size(); i++) { if(i > 0) { // add space to previous interval final TextGridInterval lastInterval = (tier.getNumberOfIntervals() > 0 ? tier.getIntervalAt(tier.getNumberOfIntervals()-1) : null); if(lastInterval != null) { lastInterval.setLabel(lastInterval.getLabel() + SPACER_TEXT); } } final IPATranscript word = ipaWords.get(i); final List<IPATranscript> sylls = word.syllables(); final float wordStart = currentStart; final float wordEnd = (i == ipaWords.size() - 1 ? end : currentStart + wordLength); final float syllLength = wordLength / sylls.size(); for(int j = 0; j < sylls.size(); j++) { final IPATranscript syll = sylls.get(j); final float syllStart = currentStart; final float syllEnd = (j == sylls.size() - 1 ? wordEnd: syllStart + syllLength); final List<String> intervals = new ArrayList<String>(); IPAElement prevPhone = null; for(IPAElement p:syll) { if(p.getScType() == SyllableConstituentType.SYLLABLEBOUNDARYMARKER || p.getScType() == SyllableConstituentType.SYLLABLESTRESSMARKER) { prevPhone = p; } else { String text = p.toString(); if(prevPhone != null) { text = prevPhone.toString() + text; prevPhone = null; } intervals.add(text); } } // add phone intervals final float phoneLength = syllLength / intervals.size(); for(int k = 0; k < intervals.size(); k++) { final String text = intervals.get(k); final float phoneStart = currentStart; final float phoneEnd = (k == intervals.size() - 1 ? syllEnd : currentStart + phoneLength); final TextGridInterval interval = new TextGridInterval(text, phoneStart, phoneEnd); tier.addInterval(interval); currentStart = phoneEnd; } } } } /* * Helper methods for adding tiers to TextGrids */ private void setupThreeIntervalTier(TextGrid textgrid, TextGridTier tier, String data) { final float start = textgrid.getMin(); float currentStart = start; final TextGridInterval firstHash = new TextGridInterval(MARKER_TEXT, start, start+MARKER_LENGTH); currentStart += MARKER_LENGTH; final float dataEnd = textgrid.getMax() - MARKER_LENGTH; final TextGridInterval dataInterval = new TextGridInterval(data, currentStart, dataEnd); currentStart = dataEnd; final TextGridInterval lastHash = new TextGridInterval(MARKER_TEXT, currentStart, textgrid.getMax()); tier.addInterval(firstHash); tier.addInterval(dataInterval); tier.addInterval(lastHash); } // public void addTierToTextGrid(IUtterance utt, String tier, ExportType type, // TextGrid textgrid, String tgName) { // // create the new textgrid tier // final TextGridTier tgTier = new TextGridTier(tgName, TextGridTierType.INTERVAL); // textgrid.addTier(tgTier); // // final SystemTierType systemTier = SystemTierType.tierFromString(tier); // final List<String> intervals = new ArrayList<String>(); // // // handle 'TIER' case here // if(type == ExportType.TIER) { // intervals.add("#"); // intervals.add(utt.getTierString(tier)); // intervals.add("#"); // } else { // if(systemTier != null) { // // if(systemTier == SystemTierType.Orthography) { // switch(type) { // case GROUP: // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // intervals.add(word.getWord()); // } // intervals.add(MARKER_TEXT); // break; // // default: // for(IWord group:utt.getWords()) { // intervals.add(MARKER_TEXT); // final String[] split = group.getWord().split("\\p{Space}"); // int widx = 0; // for(String word:split) { // if(widx++ > 0) intervals.add(SPACER_TEXT); // intervals.add(word); // } // } // intervals.add(MARKER_TEXT); // break; // } // } else if(systemTier == SystemTierType.IPATarget || systemTier == SystemTierType.IPAActual) { // switch(type) { // case GROUP: // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // final IPhoneticRep phoRep = word.getPhoneticRepresentation( // (systemTier == SystemTierType.IPATarget ? Form.Target : Form.Actual)); // intervals.add(phoRep.getTranscription()); // } // intervals.add(MARKER_TEXT); // break; // // case WORD: // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // final IPhoneticRep phoRep = word.getPhoneticRepresentation( // (systemTier == SystemTierType.IPATarget ? Form.Target : Form.Actual)); // final String group = phoRep.getTranscription(); // final String[] words = group.split("\\p{Space}"); // int widx = 0; // for(String w:words) { // if(widx++ > 0) intervals.add(SPACER_TEXT); // intervals.add(w); // } // } // intervals.add(MARKER_TEXT); // break; // // case SYLLABLE: // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // final IPhoneticRep phoRep = word.getPhoneticRepresentation( // (systemTier == SystemTierType.IPATarget ? Form.Target : Form.Actual)); // // final List<Phone> currentWord = new ArrayList<Phone>(); // for(Phone p:phoRep.getPhones()) { // int widx = 0; // if(p.getScType() == SyllableConstituentType.WordBoundaryMarker) { // if(currentWord.size() > 0) { // if(widx++ > 0) intervals.add(SPACER_TEXT); // final List<Syllable> sylls = Syllabifier.getSyllabification(currentWord); // for(Syllable syll:sylls) { // intervals.add(syll.toString()); // } // } // } // } // } // intervals.add(MARKER_TEXT); // break; // // case PHONE: // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // final IPhoneticRep phoRep = word.getPhoneticRepresentation( // (systemTier == SystemTierType.IPATarget ? Form.Target : Form.Actual)); // // final List<Phone> currentInterval = new ArrayList<Phone>(); // for(Phone p:phoRep.getPhones()) { // if(p.getScType() == SyllableConstituentType.SyllableBoundaryMarker // || p.getScType() == SyllableConstituentType.SyllableStressMarker) { // currentInterval.add(p); // } else { // String intervalText = ""; // for(Phone ph:currentInterval) { // intervalText += ph.getPhoneString(); // } // intervalText += p.getPhoneString(); // intervals.add(intervalText); // currentInterval.clear(); // } // } // } // intervals.add(MARKER_TEXT); // break; // } // } else { // intervals.add("#"); // intervals.add(utt.getTierString(tier)); // intervals.add("#"); // } // } else { // // user-defined tier // if(utt.getWordAlignedTierNames().contains(tier)) { // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // final IDependentTier depTier = word.getDependentTier(tier); // intervals.add(depTier.getTierValue()); // } // intervals.add(MARKER_TEXT); // } else { // intervals.add("#"); // intervals.add(utt.getTierString(tier)); // intervals.add("#"); // } // } // } // // // create textgrid invervals // int markerCount = 0; // int spacerCount = 0; // for(String interval:intervals) { // if(interval.equals(MARKER_TEXT)) { // markerCount++; // } else if(interval.equals(SPACER_TEXT)) { // spacerCount++; // } // } // // final float tgLength = textgrid.getMax() - textgrid.getMin(); // final float intervalsLength = tgLength - (MARKER_LENGTH * markerCount) - (SPACER_LENGTH * spacerCount); // final float intervalLength = intervalsLength / (intervals.size() - markerCount - spacerCount); // // float currentStart = textgrid.getMin(); // for(String interval:intervals) { // float len = intervalLength; // if(interval.equals(MARKER_TEXT)) { // len = MARKER_LENGTH; // } else if(interval.equals(SPACER_TEXT)) { // len = SPACER_LENGTH; // } // final TextGridInterval tgInt = new TextGridInterval(interval, currentStart, currentStart + len); // tgTier.addInterval(tgInt); // currentStart += len; // } // } /** * Create an empty textgrid from the given record. * Initializes the TextGrid with proper min/max times * * @param utt */ public TextGrid createEmptyTextGrid(Record utt) { final TextGrid retVal = new TextGrid(); final Tier<MediaSegment> segmentTier = utt.getSegment(); if(segmentTier.numberOfGroups() == 0) return retVal; final MediaSegment media = segmentTier.getGroup(0); if(media != null) { float startTime = media.getStartValue(); if(media.getUnitType() == MediaUnit.Millisecond) startTime /= 1000.0f; float endTime = media.getEndValue(); if(media.getUnitType() == MediaUnit.Millisecond) endTime /= 1000.0f; retVal.setMin(startTime); retVal.setMax(endTime); } return retVal; } /** * Export text grids for the specified session to the * given folder. * * @param session * @param recordFilter * @param exports * @param outputFolder * * @throws IOException */ public void exportTextGrids(Session session, RecordFilter recordFilter, List<TextGridExportEntry> exports, String outputFolder) throws IOException { final File folder = new File(outputFolder); if(!folder.exists()) { folder.mkdirs(); } if(!folder.isDirectory()) { throw new IllegalArgumentException("Specified path is not a folder: " + outputFolder); } for(int i = 0; i < session.getRecordCount(); i++) { final Record utt = session.getRecord(i); if(recordFilter.checkRecord(utt)) { // export text grid final TextGrid tg = new TextGrid(); setupTextGrid(utt, tg, exports); // save text grid to file final String tgFilename = utt.getUuid().toString() + (utt.getSpeaker() != null ? utt.getSpeaker().getName() : "") + ".TextGrid"; final File tgFile = new File(folder, tgFilename); TextGridManager.saveTextGrid(tg, tgFile); } } } public void exportTextGrids(Project project, Session session, RecordFilter recordFilter, List<TextGridExportEntry> exports, boolean overwrite) throws IOException { final TextGridManager tgManager = TextGridManager.getInstance(project); for(int i = 0; i < session.getRecordCount(); i++) { final Record utt = session.getRecord(i); if(recordFilter.checkRecord(utt)) { TextGrid tg = tgManager.loadTextGrid(utt.getUuid().toString()); if(tg != null && !overwrite) { continue; } // export text grid tg = createEmptyTextGrid(utt); setupTextGrid(utt, tg, exports); tgManager.saveTextGrid(tg, utt.getUuid().toString()); } } } /** * Get the location of the audio file. * */ public File getAudioFile(Project project, Session session) { File selectedMedia = MediaLocator.findMediaFile(project, session); if(selectedMedia == null) return null; File audioFile = null; int lastDot = selectedMedia.getName().lastIndexOf('.'); String mediaName = selectedMedia.getName(); if(lastDot >= 0) { mediaName = mediaName.substring(0, lastDot); } if(!selectedMedia.isAbsolute()) selectedMedia = MediaLocator.findMediaFile(session.getMediaLocation(), project, session.getCorpus()); if(selectedMedia != null) { File parentFile = selectedMedia.getParentFile(); audioFile = new File(parentFile, mediaName + ".wav"); if(!audioFile.exists()) { audioFile = null; } } return audioFile; } public void exportTextGrids(Project project, Session session, RecordFilter recordFilter, List<TextGridExportEntry> exports, String outputFolder, boolean copyExisting) throws IOException { final TextGridManager tgManager = TextGridManager.getInstance(project); final File folder = new File(outputFolder); if(!folder.exists()) { folder.mkdirs(); } if(!folder.isDirectory()) { throw new IllegalArgumentException("Specified path is not a folder: " + outputFolder); } for(int i = 0; i < session.getRecordCount(); i++) { final Record utt = session.getRecord(i); if(recordFilter.checkRecord(utt)) { TextGrid tg = tgManager.loadTextGrid(utt.getUuid().toString()); // export text grid if(tg == null || (tg != null && !copyExisting)) { tg = createEmptyTextGrid(utt); setupTextGrid(utt, tg, exports); } // save text grid to file final String tgPrefix = utt.getUuid().toString() + (utt.getSpeaker() != null ? utt.getSpeaker().getName() : ""); final String tgFilename = tgPrefix + ".TextGrid"; final File tgFile = new File(folder, tgFilename); final PraatScript ps = new PraatScript("ca/phon/plugins/praat/OpenTextGrid.vm"); final PraatScriptContext map = new PraatScriptContext(); File mediaFile = getAudioFile(project, session); if(mediaFile == null) continue; final Tier<MediaSegment> mediaTier = utt.getSegment(); if(mediaTier.numberOfGroups() == 0) continue; final MediaSegment media = mediaTier.getGroup(0); map.put("soundFile", mediaFile.getAbsolutePath()); map.put("tgFile", tgFilename); map.put("interval", media); final String script = ps.generateScript(map); TextGridManager.saveTextGrid(tg, tgFile); final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(folder, tgPrefix + ".praatscript"))); out.write(script.getBytes()); out.flush(); out.close(); } } } /** * Setup the given textgrid using settings from the * specified project. * * @param project * @param utt * @param textgrid */ public void setupTextGrid(Project project, Record utt, TextGrid textgrid) { final List<TextGridExportEntry> exports = getExports(project); setupTextGrid(utt, textgrid, exports); } public void setupTextGrid(Record utt, TextGrid textgrid, List<TextGridExportEntry> exports) { for(TextGridExportEntry entry:exports) { addTierToTextGrid(utt, textgrid, entry); } } /** * Get the list of default text grid export entries * * @return list of default exports */ public List<TextGridExportEntry> getDefaultExports() { final List<TextGridExportEntry> retVal = new ArrayList<TextGridExportEntry>(); // add orthography tiers final TextGridExportEntry ortho1 = new TextGridExportEntry(SystemTierType.Orthography.getName(), Segmentation.TIER, SystemTierType.Orthography.getName() + ": " + Segmentation.TIER.toString()); final TextGridExportEntry ortho2 = new TextGridExportEntry(SystemTierType.Orthography.getName(), Segmentation.GROUP, SystemTierType.Orthography.getName() + ": " + Segmentation.GROUP.toString()); final TextGridExportEntry ortho3 = new TextGridExportEntry(SystemTierType.Orthography.getName(), Segmentation.WORD, SystemTierType.Orthography.getName() + ": " + Segmentation.WORD.toString()); retVal.add(ortho1); retVal.add(ortho2); retVal.add(ortho3); // ipa actual final TextGridExportEntry ipa1 = new TextGridExportEntry(SystemTierType.IPAActual.getName(), Segmentation.SYLLABLE, SystemTierType.IPAActual.getName() + ": " + Segmentation.SYLLABLE.toString()); final TextGridExportEntry ipa2 = new TextGridExportEntry(SystemTierType.IPAActual.getName(), Segmentation.PHONE, SystemTierType.IPAActual.getName() + ": " + Segmentation.PHONE.toString()); retVal.add(ipa1); retVal.add(ipa2); return retVal; } /** * Get the user defined list of exports. If no export file is found, * the default list of exports is returned. * * @param project * @return textgrid export entries */ public List<TextGridExportEntry> getExports(Project project) { List<TextGridExportEntry> retVal = null; try { final String exportsFile = project.getLocation() + File.separator + EXPORT_DEFAULTS; retVal = getExportsFromFile(exportsFile); } catch (IOException e) { retVal = getDefaultExports(); } return retVal; } /** * Save the given exports the the project defaults file * * @param exports * @param project * * @return <code>true</code> if successful, <code>false</code> otherwise */ public boolean saveExports(List<TextGridExportEntry> exports, Project project) { boolean retVal = false; try { final String exportsFile = project.getLocation() + File.separator + EXPORT_DEFAULTS; saveExportsToFile(exports, exportsFile); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); } return retVal; } /** * Get the exports from the given file * * @param exportsFile * @return entries * @throws IOException */ private List<TextGridExportEntry> getExportsFromFile(String exportsFile) throws IOException { final FileInputStream fin = new FileInputStream(exportsFile); final XMLDecoder xmlDec = new XMLDecoder(fin); final List<TextGridExportEntry> retVal = new ArrayList<TextGridExportEntry>(); final Object obj = xmlDec.readObject(); if(obj != null && obj instanceof ArrayList) { final List<?> objList = (List<?>)obj; for(Object o:objList) { if(o instanceof TextGridExportEntry) { retVal.add((TextGridExportEntry)o); } } } return retVal; } /** * Save exports to file * * @param exportsFile * @throws IOException */ private void saveExportsToFile(List<TextGridExportEntry> exports, String exportsFile) throws IOException { final File file = new File(exportsFile); final File dir = file.getParentFile(); if(!dir.exists()) { dir.mkdirs(); } final FileOutputStream fout = new FileOutputStream(exportsFile); final XMLEncoder xmlEnc = new XMLEncoder(fout); xmlEnc.writeObject(exports); xmlEnc.flush(); xmlEnc.close(); } }
src/main/java/ca/phon/plugins/praat/export/TextGridExporter.java
package ca.phon.plugins.praat.export; import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import ca.phon.ipa.IPAElement; import ca.phon.ipa.IPATranscript; import ca.phon.media.util.MediaLocator; import ca.phon.plugins.praat.Segmentation; import ca.phon.plugins.praat.TextGridManager; import ca.phon.plugins.praat.script.PraatScript; import ca.phon.plugins.praat.script.PraatScriptContext; import ca.phon.project.Project; import ca.phon.session.Group; import ca.phon.session.MediaSegment; import ca.phon.session.MediaUnit; import ca.phon.session.Record; import ca.phon.session.RecordFilter; import ca.phon.session.Session; import ca.phon.session.SystemTierType; import ca.phon.session.Tier; import ca.phon.syllable.SyllableConstituentType; import ca.phon.textgrid.TextGrid; import ca.phon.textgrid.TextGridInterval; import ca.phon.textgrid.TextGridTier; import ca.phon.textgrid.TextGridTierType; import ca.phon.textgrid.TextGridWriter; /** * Utility methods for exporting Phon tier data into * TextGrids * */ public class TextGridExporter { private static final Logger LOGGER = Logger .getLogger(TextGridExporter.class.getName()); /** Default hash length in ms */ public final static float MARKER_LENGTH = 0.1f; /** Default marker interval/point text */ public final static String MARKER_TEXT = "#"; /** Default space length in ms */ public final static float SPACER_LENGTH = 0.01f; public final static String SPACER_TEXT = " "; /** * Location of text grid export defaults */ private final static String EXPORT_DEFAULTS = "__res/plugin_data/textgrid/exportdefaults.xml"; /** * Export phon tier to textgrid * * @param utt * @param textgrid * @param entry */ public void addTierToTextGrid(Record utt, TextGrid textgrid, TextGridExportEntry entry) { addTierToTextGrid(utt, entry.getPhonTier(), entry.getExportType(), textgrid, entry.getTextGridTier()); } /** * Export the specified tier from the given Phon record * into the given text grid with specified name. * * @param record * @param tier * @param type * @param textgrid * @param tgName */ public void addTierToTextGrid(Record record, String tier, Segmentation type, TextGrid textgrid, String tgName) { // create the new textgrid tier final TextGridTier tgTier = new TextGridTier(tgName, TextGridTierType.INTERVAL); textgrid.addTier(tgTier); // check if we a processing a built-in tier final SystemTierType systemTier = SystemTierType.tierFromString(tier); // calculate some values for interval times final int numHashes = record.numberOfGroups() + 1; final float totalTime = textgrid.getMax() - textgrid.getMin(); final float hashLength = MARKER_LENGTH * numHashes; final float dataLength = totalTime - hashLength; final float groupLength = dataLength / record.numberOfGroups(); // if the exportType is TIER, we create a 3-interval tier // this takes care of all flat tiers if(type == Segmentation.TIER) { setupThreeIntervalTier(textgrid, tgTier, record.getTier(tier, String.class).toString()); } else { float currentStart = textgrid.getMin(); float dataEnd = textgrid.getMax() - MARKER_LENGTH; // final List<IWord> words = utt.getWords(); for(int i = 0; i < record.numberOfGroups(); i++) { final Group group = record.getGroup(i); // add group marker final TextGridInterval marker = new TextGridInterval(MARKER_TEXT, currentStart, currentStart + MARKER_LENGTH); tgTier.addInterval(marker); currentStart += MARKER_LENGTH; // final IWord word = words.get(i); final float groupStart = currentStart; final float groupEnd = (i == record.numberOfGroups() - 1 ? dataEnd : groupStart + groupLength); if(type == Segmentation.GROUP) { String data = ""; if(systemTier != null) { if(systemTier == SystemTierType.Orthography) { data = group.getOrthography().toString(); } else if(systemTier == SystemTierType.IPATarget) { data = group.getIPATarget().toString(); } else if(systemTier == SystemTierType.IPAActual) { data = group.getIPAActual().toString(); } } else { data = group.getTier(tier).toString(); } addGroup(tgTier, data, currentStart, groupEnd); currentStart = groupEnd; } else if(type == Segmentation.WORD) { String data = ""; if(systemTier != null) { if(systemTier == SystemTierType.Orthography) { data = group.getOrthography().toString(); } else if(systemTier == SystemTierType.IPATarget) { data = group.getIPATarget().toString(); } else if(systemTier == SystemTierType.IPAActual) { data = group.getIPAActual().toString(); } } else { data = group.getTier(tier, String.class); } addWords(tgTier, data, currentStart, groupEnd); currentStart = groupEnd; } else if(type == Segmentation.SYLLABLE) { if(systemTier == SystemTierType.IPATarget || systemTier == SystemTierType.IPAActual) { addSyllables(tgTier, systemTier == SystemTierType.IPATarget ? group.getIPATarget() : group.getIPAActual(), currentStart, groupEnd); currentStart = groupEnd; } } else if(type == Segmentation.PHONE) { if(systemTier == SystemTierType.IPATarget || systemTier == SystemTierType.IPAActual) { addPhones(tgTier, systemTier == SystemTierType.IPATarget ? group.getIPATarget() : group.getIPAActual(), currentStart, groupEnd); currentStart = groupEnd; } } } // add final marker final TextGridInterval marker = new TextGridInterval(MARKER_TEXT, dataEnd, textgrid.getMax()); tgTier.addInterval(marker); } } private void addGroup(TextGridTier tier, String groupData, float start, float end) { final TextGridInterval interval = new TextGridInterval(groupData, start, end); tier.addInterval(interval); } private void addWords(TextGridTier tier, String groupData, float start, float end) { final String[] words = groupData.split("\\p{Space}"); final float wordLength = (end - start) / words.length; float currentStart = start; for(int i = 0; i < words.length; i++) { String word = words[i]; final TextGridInterval interval = new TextGridInterval(word, currentStart, (i == words.length - 1 ? end : currentStart + wordLength)); currentStart += wordLength; tier.addInterval(interval); } } private void addSyllables(TextGridTier tier, IPATranscript ipaGroup, float start, float end) { final List<IPATranscript> ipaWords = ipaGroup.words(); // calculate length of each word final float dataLength = (end - start); final float wordLength = dataLength / ipaWords.size(); // add intervals to tier float currentStart = start; for(int i = 0; i < ipaWords.size(); i++) { if(i > 0) { // add space to previous interval final TextGridInterval lastInterval = (tier.getNumberOfIntervals() > 0 ? tier.getIntervalAt(tier.getNumberOfIntervals()-1) : null); if(lastInterval != null) { lastInterval.setLabel(lastInterval.getLabel() + SPACER_TEXT); } } final IPATranscript word = ipaWords.get(i); final List<IPATranscript> sylls = word.syllables(); final float wordStart = currentStart; final float wordEnd = (i == ipaWords.size() - 1 ? end : wordStart + wordLength); final float syllLength = wordLength / sylls.size(); for(int j = 0; j < sylls.size(); j++) { final IPATranscript syll = sylls.get(j); float intEnd = (j == sylls.size() - 1 ? wordEnd : currentStart + syllLength); final TextGridInterval interval = new TextGridInterval(syll.toString(), currentStart, intEnd); tier.addInterval(interval); currentStart = intEnd; } } } private void addPhones(TextGridTier tier, IPATranscript ipaGroup, float start, float end) { final List<IPATranscript> ipaWords = ipaGroup.words(); // calculate length of each word final float dataLength = (end - start); final float wordLength = dataLength / ipaWords.size(); // add intervals to tier float currentStart = start; for(int i = 0; i < ipaWords.size(); i++) { if(i > 0) { // add space to previous interval final TextGridInterval lastInterval = (tier.getNumberOfIntervals() > 0 ? tier.getIntervalAt(tier.getNumberOfIntervals()-1) : null); if(lastInterval != null) { lastInterval.setLabel(lastInterval.getLabel() + SPACER_TEXT); } } final IPATranscript word = ipaWords.get(i); final List<IPATranscript> sylls = word.syllables(); final float wordStart = currentStart; final float wordEnd = (i == ipaWords.size() - 1 ? end : currentStart + wordLength); final float syllLength = wordLength / sylls.size(); for(int j = 0; j < sylls.size(); j++) { final IPATranscript syll = sylls.get(j); final float syllStart = currentStart; final float syllEnd = (j == sylls.size() - 1 ? wordEnd: syllStart + syllLength); final List<String> intervals = new ArrayList<String>(); IPAElement prevPhone = null; for(IPAElement p:syll) { if(p.getScType() == SyllableConstituentType.SYLLABLEBOUNDARYMARKER || p.getScType() == SyllableConstituentType.SYLLABLESTRESSMARKER) { prevPhone = p; } else { String text = p.toString(); if(prevPhone != null) { text = prevPhone.toString() + text; prevPhone = null; } intervals.add(text); } } // add phone intervals final float phoneLength = syllLength / intervals.size(); for(int k = 0; k < intervals.size(); k++) { final String text = intervals.get(k); final float phoneStart = currentStart; final float phoneEnd = (k == intervals.size() - 1 ? syllEnd : currentStart + phoneLength); final TextGridInterval interval = new TextGridInterval(text, phoneStart, phoneEnd); tier.addInterval(interval); currentStart = phoneEnd; } } } } /* * Helper methods for adding tiers to TextGrids */ private void setupThreeIntervalTier(TextGrid textgrid, TextGridTier tier, String data) { final float start = textgrid.getMin(); float currentStart = start; final TextGridInterval firstHash = new TextGridInterval(MARKER_TEXT, start, start+MARKER_LENGTH); currentStart += MARKER_LENGTH; final float dataEnd = textgrid.getMax() - MARKER_LENGTH; final TextGridInterval dataInterval = new TextGridInterval(data, currentStart, dataEnd); currentStart = dataEnd; final TextGridInterval lastHash = new TextGridInterval(MARKER_TEXT, currentStart, textgrid.getMax()); tier.addInterval(firstHash); tier.addInterval(dataInterval); tier.addInterval(lastHash); } // public void addTierToTextGrid(IUtterance utt, String tier, ExportType type, // TextGrid textgrid, String tgName) { // // create the new textgrid tier // final TextGridTier tgTier = new TextGridTier(tgName, TextGridTierType.INTERVAL); // textgrid.addTier(tgTier); // // final SystemTierType systemTier = SystemTierType.tierFromString(tier); // final List<String> intervals = new ArrayList<String>(); // // // handle 'TIER' case here // if(type == ExportType.TIER) { // intervals.add("#"); // intervals.add(utt.getTierString(tier)); // intervals.add("#"); // } else { // if(systemTier != null) { // // if(systemTier == SystemTierType.Orthography) { // switch(type) { // case GROUP: // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // intervals.add(word.getWord()); // } // intervals.add(MARKER_TEXT); // break; // // default: // for(IWord group:utt.getWords()) { // intervals.add(MARKER_TEXT); // final String[] split = group.getWord().split("\\p{Space}"); // int widx = 0; // for(String word:split) { // if(widx++ > 0) intervals.add(SPACER_TEXT); // intervals.add(word); // } // } // intervals.add(MARKER_TEXT); // break; // } // } else if(systemTier == SystemTierType.IPATarget || systemTier == SystemTierType.IPAActual) { // switch(type) { // case GROUP: // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // final IPhoneticRep phoRep = word.getPhoneticRepresentation( // (systemTier == SystemTierType.IPATarget ? Form.Target : Form.Actual)); // intervals.add(phoRep.getTranscription()); // } // intervals.add(MARKER_TEXT); // break; // // case WORD: // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // final IPhoneticRep phoRep = word.getPhoneticRepresentation( // (systemTier == SystemTierType.IPATarget ? Form.Target : Form.Actual)); // final String group = phoRep.getTranscription(); // final String[] words = group.split("\\p{Space}"); // int widx = 0; // for(String w:words) { // if(widx++ > 0) intervals.add(SPACER_TEXT); // intervals.add(w); // } // } // intervals.add(MARKER_TEXT); // break; // // case SYLLABLE: // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // final IPhoneticRep phoRep = word.getPhoneticRepresentation( // (systemTier == SystemTierType.IPATarget ? Form.Target : Form.Actual)); // // final List<Phone> currentWord = new ArrayList<Phone>(); // for(Phone p:phoRep.getPhones()) { // int widx = 0; // if(p.getScType() == SyllableConstituentType.WordBoundaryMarker) { // if(currentWord.size() > 0) { // if(widx++ > 0) intervals.add(SPACER_TEXT); // final List<Syllable> sylls = Syllabifier.getSyllabification(currentWord); // for(Syllable syll:sylls) { // intervals.add(syll.toString()); // } // } // } // } // } // intervals.add(MARKER_TEXT); // break; // // case PHONE: // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // final IPhoneticRep phoRep = word.getPhoneticRepresentation( // (systemTier == SystemTierType.IPATarget ? Form.Target : Form.Actual)); // // final List<Phone> currentInterval = new ArrayList<Phone>(); // for(Phone p:phoRep.getPhones()) { // if(p.getScType() == SyllableConstituentType.SyllableBoundaryMarker // || p.getScType() == SyllableConstituentType.SyllableStressMarker) { // currentInterval.add(p); // } else { // String intervalText = ""; // for(Phone ph:currentInterval) { // intervalText += ph.getPhoneString(); // } // intervalText += p.getPhoneString(); // intervals.add(intervalText); // currentInterval.clear(); // } // } // } // intervals.add(MARKER_TEXT); // break; // } // } else { // intervals.add("#"); // intervals.add(utt.getTierString(tier)); // intervals.add("#"); // } // } else { // // user-defined tier // if(utt.getWordAlignedTierNames().contains(tier)) { // for(IWord word:utt.getWords()) { // intervals.add(MARKER_TEXT); // final IDependentTier depTier = word.getDependentTier(tier); // intervals.add(depTier.getTierValue()); // } // intervals.add(MARKER_TEXT); // } else { // intervals.add("#"); // intervals.add(utt.getTierString(tier)); // intervals.add("#"); // } // } // } // // // create textgrid invervals // int markerCount = 0; // int spacerCount = 0; // for(String interval:intervals) { // if(interval.equals(MARKER_TEXT)) { // markerCount++; // } else if(interval.equals(SPACER_TEXT)) { // spacerCount++; // } // } // // final float tgLength = textgrid.getMax() - textgrid.getMin(); // final float intervalsLength = tgLength - (MARKER_LENGTH * markerCount) - (SPACER_LENGTH * spacerCount); // final float intervalLength = intervalsLength / (intervals.size() - markerCount - spacerCount); // // float currentStart = textgrid.getMin(); // for(String interval:intervals) { // float len = intervalLength; // if(interval.equals(MARKER_TEXT)) { // len = MARKER_LENGTH; // } else if(interval.equals(SPACER_TEXT)) { // len = SPACER_LENGTH; // } // final TextGridInterval tgInt = new TextGridInterval(interval, currentStart, currentStart + len); // tgTier.addInterval(tgInt); // currentStart += len; // } // } /** * Create an empty textgrid from the given record. * Initializes the TextGrid with proper min/max times * * @param utt */ public TextGrid createEmptyTextGrid(Record utt) { final TextGrid retVal = new TextGrid(); final Tier<MediaSegment> segmentTier = utt.getSegment(); if(segmentTier.numberOfGroups() == 0) return retVal; final MediaSegment media = segmentTier.getGroup(0); if(media != null) { float startTime = media.getStartValue(); if(media.getUnitType() == MediaUnit.Millisecond) startTime /= 1000.0f; float endTime = media.getEndValue(); if(media.getUnitType() == MediaUnit.Millisecond) endTime /= 1000.0f; retVal.setMin(startTime); retVal.setMax(endTime); } return retVal; } /** * Export text grids for the specified session to the * given folder. * * @param session * @param recordFilter * @param exports * @param outputFolder * * @throws IOException */ public void exportTextGrids(Session session, RecordFilter recordFilter, List<TextGridExportEntry> exports, String outputFolder) throws IOException { final File folder = new File(outputFolder); if(!folder.exists()) { folder.mkdirs(); } if(!folder.isDirectory()) { throw new IllegalArgumentException("Specified path is not a folder: " + outputFolder); } for(int i = 0; i < session.getRecordCount(); i++) { final Record utt = session.getRecord(i); if(recordFilter.checkRecord(utt)) { // export text grid final TextGrid tg = new TextGrid(); setupTextGrid(utt, tg, exports); // save text grid to file final String tgFilename = utt.getUuid().toString() + (utt.getSpeaker() != null ? utt.getSpeaker().getName() : "") + ".TextGrid"; final File tgFile = new File(folder, tgFilename); TextGridManager.saveTextGrid(tg, tgFile); } } } public void exportTextGrids(Project project, Session session, RecordFilter recordFilter, List<TextGridExportEntry> exports, boolean overwrite) throws IOException { final TextGridManager tgManager = TextGridManager.getInstance(project); for(int i = 0; i < session.getRecordCount(); i++) { final Record utt = session.getRecord(i); if(recordFilter.checkRecord(utt)) { TextGrid tg = tgManager.loadTextGrid(utt.getUuid().toString()); if(tg != null && !overwrite) { continue; } // export text grid tg = createEmptyTextGrid(utt); setupTextGrid(utt, tg, exports); tgManager.saveTextGrid(tg, utt.getUuid().toString()); } } } /** * Get the location of the audio file. * */ public File getAudioFile(Project project, Session session) { File selectedMedia = MediaLocator.findMediaFile(project, session); if(selectedMedia == null) return null; File audioFile = null; int lastDot = selectedMedia.getName().lastIndexOf('.'); String mediaName = selectedMedia.getName(); if(lastDot >= 0) { mediaName = mediaName.substring(0, lastDot); } if(!selectedMedia.isAbsolute()) selectedMedia = MediaLocator.findMediaFile(session.getMediaLocation(), project, session.getCorpus()); if(selectedMedia != null) { File parentFile = selectedMedia.getParentFile(); audioFile = new File(parentFile, mediaName + ".wav"); if(!audioFile.exists()) { audioFile = null; } } return audioFile; } public void exportTextGrids(Project project, Session session, RecordFilter recordFilter, List<TextGridExportEntry> exports, String outputFolder, boolean copyExisting) throws IOException { final TextGridManager tgManager = TextGridManager.getInstance(project); final File folder = new File(outputFolder); if(!folder.exists()) { folder.mkdirs(); } if(!folder.isDirectory()) { throw new IllegalArgumentException("Specified path is not a folder: " + outputFolder); } for(int i = 0; i < session.getRecordCount(); i++) { final Record utt = session.getRecord(i); if(recordFilter.checkRecord(utt)) { TextGrid tg = tgManager.loadTextGrid(utt.getUuid().toString()); // export text grid if(tg == null || (tg != null && !copyExisting)) { tg = createEmptyTextGrid(utt); setupTextGrid(utt, tg, exports); } // save text grid to file final String tgPrefix = utt.getUuid().toString() + (utt.getSpeaker() != null ? utt.getSpeaker().getName() : ""); final String tgFilename = tgPrefix + ".TextGrid"; final File tgFile = new File(folder, tgFilename); final PraatScript ps = new PraatScript("ca/phon/plugins/praat/OpenTextGrid.vm"); final PraatScriptContext map = new PraatScriptContext(); File mediaFile = getAudioFile(project, session); if(mediaFile == null) continue; final Tier<MediaSegment> mediaTier = utt.getSegment(); if(mediaTier.numberOfGroups() == 0) continue; final MediaSegment media = mediaTier.getGroup(0); map.put("soundFile", mediaFile.getAbsolutePath()); map.put("tgFile", tgFilename); map.put("interval", media); final String script = ps.generateScript(map); TextGridManager.saveTextGrid(tg, tgFile); final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(folder, tgPrefix + ".praatscript"))); out.write(script.getBytes()); out.flush(); out.close(); } } } /** * Setup the given textgrid using settings from the * specified project. * * @param project * @param utt * @param textgrid */ public void setupTextGrid(Project project, Record utt, TextGrid textgrid) { final List<TextGridExportEntry> exports = getExports(project); setupTextGrid(utt, textgrid, exports); } public void setupTextGrid(Record utt, TextGrid textgrid, List<TextGridExportEntry> exports) { for(TextGridExportEntry entry:exports) { addTierToTextGrid(utt, textgrid, entry); } } /** * Get the list of default text grid export entries * * @return list of default exports */ public List<TextGridExportEntry> getDefaultExports() { final List<TextGridExportEntry> retVal = new ArrayList<TextGridExportEntry>(); // add orthography tiers final TextGridExportEntry ortho1 = new TextGridExportEntry(SystemTierType.Orthography.getName(), Segmentation.TIER, SystemTierType.Orthography.getName() + ": " + Segmentation.TIER.toString()); final TextGridExportEntry ortho2 = new TextGridExportEntry(SystemTierType.Orthography.getName(), Segmentation.GROUP, SystemTierType.Orthography.getName() + ": " + Segmentation.GROUP.toString()); final TextGridExportEntry ortho3 = new TextGridExportEntry(SystemTierType.Orthography.getName(), Segmentation.WORD, SystemTierType.Orthography.getName() + ": " + Segmentation.WORD.toString()); retVal.add(ortho1); retVal.add(ortho2); retVal.add(ortho3); // ipa actual final TextGridExportEntry ipa1 = new TextGridExportEntry(SystemTierType.IPAActual.getName(), Segmentation.SYLLABLE, SystemTierType.IPAActual.getName() + ": " + Segmentation.SYLLABLE.toString()); final TextGridExportEntry ipa2 = new TextGridExportEntry(SystemTierType.IPAActual.getName(), Segmentation.PHONE, SystemTierType.IPAActual.getName() + ": " + Segmentation.PHONE.toString()); retVal.add(ipa1); retVal.add(ipa2); return retVal; } /** * Get the user defined list of exports. If no export file is found, * the default list of exports is returned. * * @param project * @return textgrid export entries */ public List<TextGridExportEntry> getExports(Project project) { List<TextGridExportEntry> retVal = null; try { final String exportsFile = project.getLocation() + File.separator + EXPORT_DEFAULTS; retVal = getExportsFromFile(exportsFile); } catch (IOException e) { retVal = getDefaultExports(); } return retVal; } /** * Save the given exports the the project defaults file * * @param exports * @param project * * @return <code>true</code> if successful, <code>false</code> otherwise */ public boolean saveExports(List<TextGridExportEntry> exports, Project project) { boolean retVal = false; try { final String exportsFile = project.getLocation() + File.separator + EXPORT_DEFAULTS; saveExportsToFile(exports, exportsFile); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); } return retVal; } /** * Get the exports from the given file * * @param exportsFile * @return entries * @throws IOException */ private List<TextGridExportEntry> getExportsFromFile(String exportsFile) throws IOException { final FileInputStream fin = new FileInputStream(exportsFile); final XMLDecoder xmlDec = new XMLDecoder(fin); final List<TextGridExportEntry> retVal = new ArrayList<TextGridExportEntry>(); final Object obj = xmlDec.readObject(); if(obj != null && obj instanceof ArrayList) { final List<?> objList = (List<?>)obj; for(Object o:objList) { if(o instanceof TextGridExportEntry) { retVal.add((TextGridExportEntry)o); } } } return retVal; } /** * Save exports to file * * @param exportsFile * @throws IOException */ private void saveExportsToFile(List<TextGridExportEntry> exports, String exportsFile) throws IOException { final File file = new File(exportsFile); final File dir = file.getParentFile(); if(!dir.exists()) { dir.mkdirs(); } final FileOutputStream fout = new FileOutputStream(exportsFile); final XMLEncoder xmlEnc = new XMLEncoder(fout); xmlEnc.writeObject(exports); xmlEnc.flush(); xmlEnc.close(); } }
No longer including punctuation in 'Orthography: Words' tier
src/main/java/ca/phon/plugins/praat/export/TextGridExporter.java
No longer including punctuation in 'Orthography: Words' tier
Java
bsd-3-clause
c815d3115299586beb053056b0323dc99eb9709a
0
Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo
/******************************************************************************* * Caleydo - visualization for molecular biology - http://caleydo.org * * Copyright(C) 2005, 2012 Graz University of Technology, Marc Streit, Alexander * Lex, Christian Partl, Johannes Kepler University Linz </p> * * 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 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/> *******************************************************************************/ package org.caleydo.view.datagraph.layout; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.caleydo.view.datagraph.Edge; import org.caleydo.view.datagraph.GLDataViewIntegrator; import org.caleydo.view.datagraph.Graph; import org.caleydo.view.datagraph.layout.edge.rendering.AEdgeRenderer; import org.caleydo.view.datagraph.layout.edge.rendering.FreeLayoutEdgeBandRenderer; import org.caleydo.view.datagraph.layout.edge.rendering.FreeLayoutEdgeLineRenderer; import org.caleydo.view.datagraph.layout.edge.routing.CollisionAvoidanceRoutingStrategy; import org.caleydo.view.datagraph.layout.edge.routing.IEdgeRoutingStrategy; import org.caleydo.view.datagraph.node.ADataNode; import org.caleydo.view.datagraph.node.IDVINode; import org.caleydo.view.datagraph.node.ViewNode; public class ForceDirectedGraphLayout extends AGraphLayout { // AN ALGORITHM FOR DRAWING GENERAL UNDIRECTED GRAPHS // by Tomihisa KAMADA and Satoru KAWAI, 1988 // optimization // http://www.cg.tuwien.ac.at/courses/InfoVis/HallOfFame/2005/07_Pfeffer_SpringEmbedders/pfeffer05_files/Source.pdf // data protected Map<Object, Point2D> centeredPositions = null; protected Rectangle2D layoutingArea = null; protected Collection<IDVINode> nodesToLayout = null; // calculation parameters Map<Object, Map<Object, Double>> distanceMatrix = null; Map<Object, Point2D> forces = null; double diameter = 0.0; double scalingFactor = 1.0; double L = 0.0; double K = 1; protected double constraintStartingFactor = 1.0; protected double constraintDecrease = 0.0; protected double constraintFactor = 1.0; protected boolean running = true; protected boolean initializeNodes = true; protected boolean initializeForces = true; protected boolean initializeConstraints = false; protected IEdgeRoutingStrategy edgeRoutingStrategy; public ForceDirectedGraphLayout(GLDataViewIntegrator view, Graph graph) { super(view, graph); edgeRoutingStrategy = new CollisionAvoidanceRoutingStrategy(graph); } // ################### // ## layout source ## // ################### public void setGraph(Graph graph) { this.graph = graph; initializeNodes = true; initializeForces = true; running = true; } protected boolean isDataAvailable() { if (graph == null) return false; if (graph.getNumberOfNodes() == 0) return false; return true; } // ##################### // ## distance matrix ## // ##################### private void setDistance(Object node1, Object node2, Double distance) { if (distanceMatrix == null) { distanceMatrix = new HashMap<Object, Map<Object, Double>>(); } Map<Object, Double> map = distanceMatrix.get(node1); if (map == null) { map = new HashMap<Object, Double>(); distanceMatrix.put(node1, map); } map.put(node2, distance); map = distanceMatrix.get(node2); if (map == null) { map = new HashMap<Object, Double>(); distanceMatrix.put(node2, map); } map.put(node1, distance); } private double getDistance(Object node1, Object node2) { if (node1 == node2) return 0; if (distanceMatrix == null) return Double.POSITIVE_INFINITY; Map<Object, Double> map = distanceMatrix.get(node1); if (map == null) return Double.POSITIVE_INFINITY; Double distance = map.get(node2); if (distance == null) return Double.POSITIVE_INFINITY; return distance; } protected double getL(Object node1, Object node2) { Double distance = getDistance(node1, node2); if (distance == Double.POSITIVE_INFINITY) { return 0.5; } return L * distance; } protected double getK(Object node1, Object node2) { Double distance = getDistance(node1, node2); if (distance == Double.POSITIVE_INFINITY) { return K / (diameter * diameter); } else if (distance == 0) { return 1; } return K / (distance * distance); } private void calculateDistanceMatrix() { // http://de.wikipedia.org/wiki/Floyd-Warshall-Algorithmus diameter = 1.0; if (!isDataAvailable()) return; // initialize with available edges for (IDVINode node1 : graph.getNodes()) { for (IDVINode node2 : graph.getNodes()) { if (graph.incident(node1, node2)) { setDistance(node1, node2, 1.0); } } } // calculate distances for (IDVINode nodek : graph.getNodes()) { for (IDVINode nodei : graph.getNodes()) { for (IDVINode nodej : graph.getNodes()) { setDistance( nodei, nodej, Math.min(getDistance(nodei, nodej), getDistance(nodei, nodek) + getDistance(nodek, nodej))); } } } // calculate diameter double distance; diameter = 1.0; for (Object node1 : graph.getNodes()) { for (Object node2 : graph.getNodes()) { distance = getDistance(node1, node2); if (distance != Double.POSITIVE_INFINITY) { diameter = Math.max(diameter, distance); } } } } // ############ // ## deltas ## // ############ protected Point2D calculateDelta(Object node) { // dx = (-eq7 - eq14 dy) / eq13 // dy = (eq7 eq15 - eq8 eq13) / (eq13 eq16 - eq14 eq15) double deltaX = 0.0; double deltaY = 0.0; double[] eqs = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; // eq7 = 0 | eq8 = 1 | eq13 = 2 | eq14 = 3 | eq15 = 4 | eq16 = 5 for (Object node2 : nodesToLayout) { if (node != node2) { calculateDelta(node, node2, eqs); } } deltaY = (eqs[2] * eqs[5] - eqs[3] * eqs[4]); if (deltaY != 0.0) { deltaY = (eqs[0] * eqs[4] - eqs[1] * eqs[2]) / deltaY; } if (eqs[2] == 0.0) { deltaX = 0.0; } else { deltaX = (-eqs[0] - eqs[3] * deltaY) / eqs[2]; } return new Point2D.Double(deltaX, deltaY); } protected void calculateDelta(Object node1, Object node2, double[] eqs) { // pre calculation Point2D p1 = getNodePosition(node1, false); Point2D p2 = getNodePosition(node2, false); double k = getK(node1, node2); double l = getL(node1, node2); double dx = p1.getX() - p2.getX(); double dy = p1.getY() - p2.getY(); double dx2 = dx * dx; double dy2 = dy * dy; // calculate divisor double divisor = dx2 + dy2; double divisor7_8 = Math.sqrt(divisor); if (divisor7_8 == 0.0) divisor7_8 = 1.0; double divisor13_16 = Math.pow(divisor, 1.5); if (divisor13_16 == 0.0) divisor7_8 = 1.0; // calculate equations eqs[0] += k * dx * (1 - l / divisor7_8); eqs[1] += k * dy * (1 - l / divisor7_8); eqs[2] += k * (1 - l * dy2 / divisor13_16); eqs[3] += k * l * dx * dy / divisor13_16; eqs[4] += k * l * dx * dy / divisor13_16; eqs[5] += k * (1 - l * dx2 / divisor13_16); } // ############ // ## forces ## // ############ private void setForce(Object node, Point2D force) { if (forces == null) { forces = new HashMap<Object, Point2D>(); } forces.put(node, force); } private Point2D getForce(Object node) { if (forces == null) return null; return forces.get(node); } private boolean forcesWithoutError() { for (Object node : nodesToLayout) { Point2D force = getForce(node); if (force == null) continue; if (Double.isNaN(force.getX()) || Double.isNaN(force.getY())) return false; } return true; } protected Point2D calculateForce(Object node) { double[] deltas = { 0.0, 0.0 }; for (Object node2 : nodesToLayout) { if (node != node2) { calculateForce(node, node2, deltas); } } return new Point2D.Double(deltas[0], deltas[1]); } protected void calculateForce(Object node1, Object node2, double[] deltas) { Point2D p1 = getNodePosition(node1, false); Point2D p2 = getNodePosition(node2, false); double k = getK(node1, node2); double l = getL(node1, node2); double dx = p1.getX() - p2.getX(); double dy = p1.getY() - p2.getY(); double dx2 = dx * dx; double dy2 = dy * dy; // calculate divisor double divisor = dx2 + dy2; double divisor7_8 = Math.sqrt(divisor); if (divisor7_8 == 0.0) divisor7_8 = 1.0; // calculate equations deltas[0] += k * dx * (1 - l / divisor7_8); deltas[1] += k * dy * (1 - l / divisor7_8); } protected Point2D calculateForceInfluence(Object node, Object influencer) { double deltaX = 0.0; double deltaY = 0.0; double dx; double dx2; double dy; double dy2; double divisor; double divisor7_8; double k; double l; Point2D p1 = getNodePosition(node, false); Point2D p2 = getNodePosition(influencer, false); k = getK(node, influencer); l = getL(node, influencer); dx = p1.getX() - p2.getX(); dy = p1.getY() - p2.getY(); dx2 = dx * dx; dy2 = dy * dy; // calculate divisor divisor = dx2 + dy2; divisor7_8 = Math.sqrt(divisor); if (divisor7_8 == 0.0) divisor7_8 = 1.0; // calculate equations deltaX = k * dx * (1 - l / divisor7_8); deltaY = k * dy * (1 - l / divisor7_8); return new Point2D.Double(deltaX, deltaY); } // ######################## // ## layout calculation ## // ######################## @Override public void layout(Rectangle2D area) { if (area == null) return; boolean equalAreas = area.equals(layoutingArea); layoutingArea = area; running = false; if (graph == null) return; if (graph.getNumberOfNodes() == 0) return; nodesToLayout = getNodesToLayout(); if (nodesToLayout == null) return; // // initializations // if (initializeNodes) { initializeNodePositions(); calculateDistanceMatrix(); centering(); initializeNodes = false; // } if (!graph.hasEdges()) return; // if (initializeForces || !forcesWithoutError()) { initializeForces(); initializeForces = false; // } running = true; L = scalingFactor * Math.max(10, Math.min(area.getWidth(), area.getHeight())) / diameter; // find biggest delta int numberOfNodesSet = 100; double forceMax = 0.0; boolean nodeSet = false; while (numberOfNodesSet > 0) { numberOfNodesSet--; double forceLength; forceMax = 0.0; Object nodeMax = null; ; Point2D force; for (Object node : nodesToLayout) { force = getForce(node); if (force == null) { forceLength = 0; } else { forceLength = force.distance(0, 0); } if (forceLength > forceMax) { forceMax = forceLength; nodeMax = node; } } if (forceMax > 1) { nodeSet = true; Point2D pos = getNodePosition(nodeMax, false); Point2D delta = calculateDelta(nodeMax); substractForceInfluence(nodeMax); pos.setLocation(pos.getX() + delta.getX(), pos.getY() + delta.getY()); addForceInfluence(nodeMax); initializeForce(nodeMax); } else { numberOfNodesSet = 0; } constraintFactor -= constraintDecrease; if (constraintFactor < 0) { constraintFactor = 0; } } if (nodeSet || !equalAreas) { centering(); } if (forceMax <= 1) { running = false; } for (IDVINode node : nodesToLayout) { node.setUpsideDown(false); } updateNodePositions(); } @Override public void updateNodePositions() { if (nodesToLayout == null) return; for (IDVINode node : nodesToLayout) { Point2D nodePosition = getNodePosition(node); if (nodePosition == null) continue; double nodePositionX = nodePosition.getX(); if (nodePositionX + node.getWidthPixels() / 2.0f > layoutingArea.getMaxX()) { nodePositionX = layoutingArea.getMaxX() - node.getWidthPixels() / 2.0f; } else if (nodePositionX - node.getWidthPixels() / 2.0f < layoutingArea .getMinX()) { nodePositionX = layoutingArea.getMinX() + node.getWidthPixels() / 2.0f; } double nodePositionY = getNodePosition(node).getY(); if (nodePositionY + node.getHeightPixels() / 2.0f > layoutingArea.getMaxY()) { nodePositionY = layoutingArea.getMaxY() - node.getHeightPixels() / 2.0f; } else if (nodePositionY - node.getHeightPixels() / 2.0f < layoutingArea .getMinY()) { nodePositionY = layoutingArea.getMinY() + node.getHeightPixels() / 2.0f; } setNodePosition(node, new Point2D.Float((float) nodePositionX, (float) nodePositionY)); } view.setNodePositionsUpdated(true); } protected Collection<IDVINode> getNodesToLayout() { return graph.getNodes(); } protected void initializeNodePositions() { if (graph == null) return; if (graph.getNumberOfNodes() == 0) return; if (nodePositions == null) { nodePositions = new HashMap<Object, Point2D>(); } if (centeredPositions == null) { centeredPositions = new HashMap<Object, Point2D>(); } Point2D point; double arc = 0; double arcStep = 2 * Math.PI / graph.getNumberOfNodes(); double radius = Math.min(layoutingArea.getWidth(), layoutingArea.getHeight()) / 2.5; double centerX = layoutingArea.getWidth() / 2.0; double centerY = layoutingArea.getHeight() / 2.0; for (Object node : graph.getNodes()) { if (!isPositionAvailable(node)) { point = new Point2D.Double(centerX + radius * Math.sin(arc), centerY + radius * Math.cos(arc)); nodePositions.put(node, point); centeredPositions.put(node, point); arc += arcStep; } } } private boolean isPositionAvailable(Object node) { if (nodePositions == null) return false; Point2D pos = nodePositions.get(node); if (pos == null) return false; if (Double.isNaN(pos.getX()) || Double.isNaN(pos.getY())) return false; return true; } private void initializeForces() { Point2D force; for (Object node : graph.getNodes()) { force = calculateForce(node); setForce(node, force); } } private void initializeForce(Object node) { Point2D force; force = calculateForce(node); setForce(node, force); } private void substractForceInfluence(Object influencer) { Point2D force, subtractForce; for (Object node : graph.getNodes()) { if (node != influencer) { force = getForce(node); subtractForce = calculateForceInfluence(node, influencer); force.setLocation(force.getX() - subtractForce.getX(), force.getY() - subtractForce.getY()); } } } private void addForceInfluence(Object influencer) { Point2D force, addDelta; for (Object node : graph.getNodes()) { if (node != influencer) { force = getForce(node); addDelta = calculateForceInfluence(node, influencer); force.setLocation(force.getX() + addDelta.getX(), force.getY() + addDelta.getY()); } } } protected void centering() { if (nodesToLayout.size() == 1) { for (Object node : nodesToLayout) { centeredPositions.put(node, new Point2D.Double( layoutingArea.getCenterX(), layoutingArea.getCenterY())); } return; } // determine center double minX = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; Point2D point; for (Object node : nodesToLayout) { point = getNodePosition(node, false); minX = Math.min(minX, point.getX()); maxX = Math.max(maxX, point.getX()); minY = Math.min(minY, point.getY()); maxY = Math.max(maxY, point.getY()); } // update scaling double fx = maxX == minX ? 1 : (layoutingArea.getWidth()) / (maxX - minX); double fy = maxY == minY ? 1 : (layoutingArea.getHeight()) / (maxY - minY); double offsetX = layoutingArea.getMinX(); double offsetY = layoutingArea.getMinY(); // double factor = 1.0; // if (fx < fy) { // factor = fx; // // offsetY += (layoutingArea.getHeight() - factor * (maxY-minY)) / 2; // } else { // factor = fy; // // offsetX += (layoutingArea.getWidth() - factor * (maxX-minX)) / 2; // } for (Object node : nodesToLayout) { point = getNodePosition(node, false); centeredPositions.put(node, new Point2D.Double((point.getX() - minX) * fx + offsetX, (point.getY() - minY) * fy + offsetY)); } } public boolean layoutInProgress() { return running; } // --- setter --- // nodes @Override public void setNodePosition(Object node, Point2D position) { // TODO Auto-generated method stub nodePositions.put(node, position); centeredPositions.put(node, position); } // --- getter --- // node position @Override public Point2D getNodePosition(Object node) { return getNodePosition(node, true); } public Point2D getNodePosition(Object node, boolean centered) { if (centered) { if (centeredPositions == null) return null; return centeredPositions.get(node); } else { if (nodePositions == null) return null; return nodePositions.get(node); } } @Override public void clearNodePositions() { if (centeredPositions != null) centeredPositions.clear(); centeredPositions = null; if (nodePositions != null) nodePositions.clear(); nodePositions = null; } @Override public AEdgeRenderer getLayoutSpecificEdgeRenderer(Edge edge) { IDVINode node1 = edge.getNode1(); IDVINode node2 = edge.getNode2(); AEdgeRenderer edgeRenderer = null; if (node1 instanceof ViewNode || node2 instanceof ViewNode) { edgeRenderer = new FreeLayoutEdgeBandRenderer(edge, view); } else { edgeRenderer = new FreeLayoutEdgeLineRenderer(edge, view, view.getEdgeLabel((ADataNode) node1, (ADataNode) node2)); } edgeRenderer.setEdgeRoutingStrategy(edgeRoutingStrategy); return edgeRenderer; } @Override public AEdgeRenderer getCustomLayoutEdgeRenderer(Edge edge) { return getLayoutSpecificEdgeRenderer(edge); } }
org.caleydo.view.datagraph/src/org/caleydo/view/datagraph/layout/ForceDirectedGraphLayout.java
/******************************************************************************* * Caleydo - visualization for molecular biology - http://caleydo.org * * Copyright(C) 2005, 2012 Graz University of Technology, Marc Streit, Alexander * Lex, Christian Partl, Johannes Kepler University Linz </p> * * 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 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/> *******************************************************************************/ package org.caleydo.view.datagraph.layout; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.caleydo.view.datagraph.Edge; import org.caleydo.view.datagraph.GLDataViewIntegrator; import org.caleydo.view.datagraph.Graph; import org.caleydo.view.datagraph.layout.edge.rendering.AEdgeRenderer; import org.caleydo.view.datagraph.layout.edge.rendering.FreeLayoutEdgeBandRenderer; import org.caleydo.view.datagraph.layout.edge.rendering.FreeLayoutEdgeLineRenderer; import org.caleydo.view.datagraph.layout.edge.routing.CollisionAvoidanceRoutingStrategy; import org.caleydo.view.datagraph.layout.edge.routing.IEdgeRoutingStrategy; import org.caleydo.view.datagraph.node.ADataNode; import org.caleydo.view.datagraph.node.IDVINode; import org.caleydo.view.datagraph.node.ViewNode; public class ForceDirectedGraphLayout extends AGraphLayout { // AN ALGORITHM FOR DRAWING GENERAL UNDIRECTED GRAPHS // by Tomihisa KAMADA and Satoru KAWAI, 1988 // optimization // http://www.cg.tuwien.ac.at/courses/InfoVis/HallOfFame/2005/07_Pfeffer_SpringEmbedders/pfeffer05_files/Source.pdf // data protected Map<Object, Point2D> centeredPositions = null; protected Rectangle2D layoutingArea = null; protected Collection<IDVINode> nodesToLayout = null; // calculation parameters Map<Object, Map<Object, Double>> distanceMatrix = null; Map<Object, Point2D> forces = null; double diameter = 0.0; double scalingFactor = 1.0; double L = 0.0; double K = 1; protected double constraintStartingFactor = 1.0; protected double constraintDecrease = 0.0; protected double constraintFactor = 1.0; protected boolean running = true; protected boolean initializeNodes = true; protected boolean initializeForces = true; protected boolean initializeConstraints = false; protected IEdgeRoutingStrategy edgeRoutingStrategy; public ForceDirectedGraphLayout(GLDataViewIntegrator view, Graph graph) { super(view, graph); edgeRoutingStrategy = new CollisionAvoidanceRoutingStrategy(graph); } // ################### // ## layout source ## // ################### public void setGraph(Graph graph) { this.graph = graph; initializeNodes = true; initializeForces = true; running = true; } protected boolean isDataAvailable() { if (graph == null) return false; if (graph.getNumberOfNodes() == 0) return false; return true; } // ##################### // ## distance matrix ## // ##################### private void setDistance(Object node1, Object node2, Double distance) { if (distanceMatrix == null) { distanceMatrix = new HashMap<Object, Map<Object, Double>>(); } Map<Object, Double> map = distanceMatrix.get(node1); if (map == null) { map = new HashMap<Object, Double>(); distanceMatrix.put(node1, map); } map.put(node2, distance); map = distanceMatrix.get(node2); if (map == null) { map = new HashMap<Object, Double>(); distanceMatrix.put(node2, map); } map.put(node1, distance); } private double getDistance(Object node1, Object node2) { if (node1 == node2) return 0; if (distanceMatrix == null) return Double.POSITIVE_INFINITY; Map<Object, Double> map = distanceMatrix.get(node1); if (map == null) return Double.POSITIVE_INFINITY; Double distance = map.get(node2); if (distance == null) return Double.POSITIVE_INFINITY; return distance; } protected double getL(Object node1, Object node2) { Double distance = getDistance(node1, node2); if (distance == Double.POSITIVE_INFINITY) { return 0.5; } return L * distance; } protected double getK(Object node1, Object node2) { Double distance = getDistance(node1, node2); if (distance == Double.POSITIVE_INFINITY) { return K / (diameter * diameter); } else if (distance == 0) { return 1; } return K / (distance * distance); } private void calculateDistanceMatrix() { // http://de.wikipedia.org/wiki/Floyd-Warshall-Algorithmus diameter = 1.0; if (!isDataAvailable()) return; // initialize with available edges for (IDVINode node1 : graph.getNodes()) { for (IDVINode node2 : graph.getNodes()) { if (graph.incident(node1, node2)) { setDistance(node1, node2, 1.0); } } } // calculate distances for (IDVINode nodek : graph.getNodes()) { for (IDVINode nodei : graph.getNodes()) { for (IDVINode nodej : graph.getNodes()) { setDistance( nodei, nodej, Math.min(getDistance(nodei, nodej), getDistance(nodei, nodek) + getDistance(nodek, nodej))); } } } // calculate diameter double distance; diameter = 1.0; for (Object node1 : graph.getNodes()) { for (Object node2 : graph.getNodes()) { distance = getDistance(node1, node2); if (distance != Double.POSITIVE_INFINITY) { diameter = Math.max(diameter, distance); } } } } // ############ // ## deltas ## // ############ protected Point2D calculateDelta(Object node) { // dx = (-eq7 - eq14 dy) / eq13 // dy = (eq7 eq15 - eq8 eq13) / (eq13 eq16 - eq14 eq15) double deltaX = 0.0; double deltaY = 0.0; double[] eqs = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; // eq7 = 0 | eq8 = 1 | eq13 = 2 | eq14 = 3 | eq15 = 4 | eq16 = 5 for (Object node2 : nodesToLayout) { if (node != node2) { calculateDelta(node, node2, eqs); } } deltaY = (eqs[2] * eqs[5] - eqs[3] * eqs[4]); if (deltaY != 0.0) { deltaY = (eqs[0] * eqs[4] - eqs[1] * eqs[2]) / deltaY; } if (eqs[2] == 0.0) { deltaX = 0.0; } else { deltaX = (-eqs[0] - eqs[3] * deltaY) / eqs[2]; } return new Point2D.Double(deltaX, deltaY); } protected void calculateDelta(Object node1, Object node2, double[] eqs) { // pre calculation Point2D p1 = getNodePosition(node1, false); Point2D p2 = getNodePosition(node2, false); double k = getK(node1, node2); double l = getL(node1, node2); double dx = p1.getX() - p2.getX(); double dy = p1.getY() - p2.getY(); double dx2 = dx * dx; double dy2 = dy * dy; // calculate divisor double divisor = dx2 + dy2; double divisor7_8 = Math.sqrt(divisor); if (divisor7_8 == 0.0) divisor7_8 = 1.0; double divisor13_16 = Math.pow(divisor, 1.5); if (divisor13_16 == 0.0) divisor7_8 = 1.0; // calculate equations eqs[0] += k * dx * (1 - l / divisor7_8); eqs[1] += k * dy * (1 - l / divisor7_8); eqs[2] += k * (1 - l * dy2 / divisor13_16); eqs[3] += k * l * dx * dy / divisor13_16; eqs[4] += k * l * dx * dy / divisor13_16; eqs[5] += k * (1 - l * dx2 / divisor13_16); } // ############ // ## forces ## // ############ private void setForce(Object node, Point2D force) { if (forces == null) { forces = new HashMap<Object, Point2D>(); } forces.put(node, force); } private Point2D getForce(Object node) { if (forces == null) return null; return forces.get(node); } private boolean forcesWithoutError() { for (Object node : nodesToLayout) { Point2D force = getForce(node); if (force == null) continue; if (Double.isNaN(force.getX()) || Double.isNaN(force.getY())) return false; } return true; } protected Point2D calculateForce(Object node) { double[] deltas = { 0.0, 0.0 }; for (Object node2 : nodesToLayout) { if (node != node2) { calculateForce(node, node2, deltas); } } return new Point2D.Double(deltas[0], deltas[1]); } protected void calculateForce(Object node1, Object node2, double[] deltas) { Point2D p1 = getNodePosition(node1, false); Point2D p2 = getNodePosition(node2, false); double k = getK(node1, node2); double l = getL(node1, node2); double dx = p1.getX() - p2.getX(); double dy = p1.getY() - p2.getY(); double dx2 = dx * dx; double dy2 = dy * dy; // calculate divisor double divisor = dx2 + dy2; double divisor7_8 = Math.sqrt(divisor); if (divisor7_8 == 0.0) divisor7_8 = 1.0; // calculate equations deltas[0] += k * dx * (1 - l / divisor7_8); deltas[1] += k * dy * (1 - l / divisor7_8); } protected Point2D calculateForceInfluence(Object node, Object influencer) { double deltaX = 0.0; double deltaY = 0.0; double dx; double dx2; double dy; double dy2; double divisor; double divisor7_8; double k; double l; Point2D p1 = getNodePosition(node, false); Point2D p2 = getNodePosition(influencer, false); k = getK(node, influencer); l = getL(node, influencer); dx = p1.getX() - p2.getX(); dy = p1.getY() - p2.getY(); dx2 = dx * dx; dy2 = dy * dy; // calculate divisor divisor = dx2 + dy2; divisor7_8 = Math.sqrt(divisor); if (divisor7_8 == 0.0) divisor7_8 = 1.0; // calculate equations deltaX = k * dx * (1 - l / divisor7_8); deltaY = k * dy * (1 - l / divisor7_8); return new Point2D.Double(deltaX, deltaY); } // ######################## // ## layout calculation ## // ######################## @Override public void layout(Rectangle2D area) { if (area == null) return; boolean equalAreas = area.equals(layoutingArea); layoutingArea = area; running = false; if (graph == null) return; if (graph.getNumberOfNodes() == 0) return; nodesToLayout = getNodesToLayout(); if (nodesToLayout == null) return; // initializations if (initializeNodes) { initializeNodePositions(); calculateDistanceMatrix(); centering(); initializeNodes = false; } if (!graph.hasEdges()) return; if (initializeForces || !forcesWithoutError()) { initializeForces(); initializeForces = false; } running = true; L = scalingFactor * Math.max(10, Math.min(area.getWidth(), area.getHeight())) / diameter; // find biggest delta int numberOfNodesSet = 100; double forceMax = 0.0; boolean nodeSet = false; while (numberOfNodesSet > 0) { numberOfNodesSet--; double forceLength; forceMax = 0.0; Object nodeMax = null; ; Point2D force; for (Object node : nodesToLayout) { force = getForce(node); if (force == null) { forceLength = 0; } else { forceLength = force.distance(0, 0); } if (forceLength > forceMax) { forceMax = forceLength; nodeMax = node; } } if (forceMax > 1) { nodeSet = true; Point2D pos = getNodePosition(nodeMax, false); Point2D delta = calculateDelta(nodeMax); substractForceInfluence(nodeMax); pos.setLocation(pos.getX() + delta.getX(), pos.getY() + delta.getY()); addForceInfluence(nodeMax); initializeForce(nodeMax); } else { numberOfNodesSet = 0; } constraintFactor -= constraintDecrease; if (constraintFactor < 0) { constraintFactor = 0; } } if (nodeSet || !equalAreas) { centering(); } if (forceMax <= 1) { running = false; } for (IDVINode node : nodesToLayout) { node.setUpsideDown(false); } updateNodePositions(); } @Override public void updateNodePositions() { if (nodesToLayout == null) return; for (IDVINode node : nodesToLayout) { Point2D nodePosition = getNodePosition(node); if (nodePosition == null) continue; double nodePositionX = nodePosition.getX(); if (nodePositionX + node.getWidthPixels() / 2.0f > layoutingArea.getMaxX()) { nodePositionX = layoutingArea.getMaxX() - node.getWidthPixels() / 2.0f; } else if (nodePositionX - node.getWidthPixels() / 2.0f < layoutingArea .getMinX()) { nodePositionX = layoutingArea.getMinX() + node.getWidthPixels() / 2.0f; } double nodePositionY = getNodePosition(node).getY(); if (nodePositionY + node.getHeightPixels() / 2.0f > layoutingArea.getMaxY()) { nodePositionY = layoutingArea.getMaxY() - node.getHeightPixels() / 2.0f; } else if (nodePositionY - node.getHeightPixels() / 2.0f < layoutingArea .getMinY()) { nodePositionY = layoutingArea.getMinY() + node.getHeightPixels() / 2.0f; } setNodePosition(node, new Point2D.Float((float) nodePositionX, (float) nodePositionY)); } view.setNodePositionsUpdated(true); } protected Collection<IDVINode> getNodesToLayout() { return graph.getNodes(); } protected void initializeNodePositions() { if (graph == null) return; if (graph.getNumberOfNodes() == 0) return; if (nodePositions == null) { nodePositions = new HashMap<Object, Point2D>(); } if (centeredPositions == null) { centeredPositions = new HashMap<Object, Point2D>(); } Point2D point; double arc = 0; double arcStep = 2 * Math.PI / graph.getNumberOfNodes(); double radius = Math.min(layoutingArea.getWidth(), layoutingArea.getHeight()) / 2.5; double centerX = layoutingArea.getWidth() / 2.0; double centerY = layoutingArea.getHeight() / 2.0; for (Object node : graph.getNodes()) { if (!isPositionAvailable(node)) { point = new Point2D.Double(centerX + radius * Math.sin(arc), centerY + radius * Math.cos(arc)); nodePositions.put(node, point); centeredPositions.put(node, point); arc += arcStep; } } } private boolean isPositionAvailable(Object node) { if (nodePositions == null) return false; Point2D pos = nodePositions.get(node); if (pos == null) return false; if (Double.isNaN(pos.getX()) || Double.isNaN(pos.getY())) return false; return true; } private void initializeForces() { Point2D force; for (Object node : graph.getNodes()) { force = calculateForce(node); setForce(node, force); } } private void initializeForce(Object node) { Point2D force; force = calculateForce(node); setForce(node, force); } private void substractForceInfluence(Object influencer) { Point2D force, subtractForce; for (Object node : graph.getNodes()) { if (node != influencer) { force = getForce(node); subtractForce = calculateForceInfluence(node, influencer); force.setLocation(force.getX() - subtractForce.getX(), force.getY() - subtractForce.getY()); } } } private void addForceInfluence(Object influencer) { Point2D force, addDelta; for (Object node : graph.getNodes()) { if (node != influencer) { force = getForce(node); addDelta = calculateForceInfluence(node, influencer); force.setLocation(force.getX() + addDelta.getX(), force.getY() + addDelta.getY()); } } } protected void centering() { if (nodesToLayout.size() == 1) { for (Object node : nodesToLayout) { centeredPositions.put(node, new Point2D.Double( layoutingArea.getCenterX(), layoutingArea.getCenterY())); } return; } // determine center double minX = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; Point2D point; for (Object node : nodesToLayout) { point = getNodePosition(node, false); minX = Math.min(minX, point.getX()); maxX = Math.max(maxX, point.getX()); minY = Math.min(minY, point.getY()); maxY = Math.max(maxY, point.getY()); } // update scaling double fx = maxX == minX ? 1 : (layoutingArea.getWidth()) / (maxX - minX); double fy = maxY == minY ? 1 : (layoutingArea.getHeight()) / (maxY - minY); double offsetX = layoutingArea.getMinX(); double offsetY = layoutingArea.getMinY(); // double factor = 1.0; // if (fx < fy) { // factor = fx; // // offsetY += (layoutingArea.getHeight() - factor * (maxY-minY)) / 2; // } else { // factor = fy; // // offsetX += (layoutingArea.getWidth() - factor * (maxX-minX)) / 2; // } for (Object node : nodesToLayout) { point = getNodePosition(node, false); centeredPositions.put(node, new Point2D.Double((point.getX() - minX) * fx + offsetX, (point.getY() - minY) * fy + offsetY)); } } public boolean layoutInProgress() { return running; } // --- setter --- // nodes @Override public void setNodePosition(Object node, Point2D position) { // TODO Auto-generated method stub nodePositions.put(node, position); centeredPositions.put(node, position); } // --- getter --- // node position @Override public Point2D getNodePosition(Object node) { return getNodePosition(node, true); } public Point2D getNodePosition(Object node, boolean centered) { if (centered) { if (centeredPositions == null) return null; return centeredPositions.get(node); } else { if (nodePositions == null) return null; return nodePositions.get(node); } } @Override public void clearNodePositions() { if (centeredPositions != null) centeredPositions.clear(); centeredPositions = null; if (nodePositions != null) nodePositions.clear(); nodePositions = null; } @Override public AEdgeRenderer getLayoutSpecificEdgeRenderer(Edge edge) { IDVINode node1 = edge.getNode1(); IDVINode node2 = edge.getNode2(); AEdgeRenderer edgeRenderer = null; if (node1 instanceof ViewNode || node2 instanceof ViewNode) { edgeRenderer = new FreeLayoutEdgeBandRenderer(edge, view); } else { edgeRenderer = new FreeLayoutEdgeLineRenderer(edge, view, view.getEdgeLabel((ADataNode) node1, (ADataNode) node2)); } edgeRenderer.setEdgeRoutingStrategy(edgeRoutingStrategy); return edgeRenderer; } @Override public AEdgeRenderer getCustomLayoutEdgeRenderer(Edge edge) { return getLayoutSpecificEdgeRenderer(edge); } }
Fixed NPE in DVI that occurred when adding a node in force directed layout. git-svn-id: 149221363d454b9399d51e0b24a857a738336ca8@4837 1f7349ae-fd9f-0d40-aeb8-9798e6c0fce3
org.caleydo.view.datagraph/src/org/caleydo/view/datagraph/layout/ForceDirectedGraphLayout.java
Fixed NPE in DVI that occurred when adding a node in force directed layout.
Java
bsd-3-clause
8d198dee8412065d1e1aa73b68ebce85a954c3f9
0
LukSkarDev/modules,martokarski/modules,wstrzelczyk/modules,shubhambeehyv/modules,ScottKimball/modules,mkwiatkowskisoldevelo/modules,koshalt/modules,justin-hayes/modules,ngraczewski/modules,tstalka/modules,smalecki/modules,atish160384/modules,atish160384/modules,justin-hayes/modules,ngraczewski/modules,pmuchowski/modules,sebbrudzinski/modules,tstalka/modules,frankhuster/modules,frankhuster/modules,shubhambeehyv/modules,sebbrudzinski/modules,LukSkarDev/modules,martokarski/modules,LukSkarDev/modules,koshalt/modules,martokarski/modules,ScottKimball/modules,justin-hayes/modules,shubhambeehyv/modules,tstalka/modules,ngraczewski/modules,sebbrudzinski/modules,smalecki/modules,mkwiatkowskisoldevelo/modules,ScottKimball/modules,pmuchowski/modules,1stmateusz/modules,frankhuster/modules,1stmateusz/modules,wstrzelczyk/modules,wstrzelczyk/modules,pgesek/modules,justin-hayes/modules,pgesek/modules,atish160384/modules,wstrzelczyk/modules,ngraczewski/modules,atish160384/modules,1stmateusz/modules,smalecki/modules,tstalka/modules,smalecki/modules,mkwiatkowskisoldevelo/modules,pmuchowski/modules,ScottKimball/modules,koshalt/modules,shubhambeehyv/modules,1stmateusz/modules,martokarski/modules,pgesek/modules,pmuchowski/modules,LukSkarDev/modules,sebbrudzinski/modules,mkwiatkowskisoldevelo/modules,frankhuster/modules,pgesek/modules,koshalt/modules
package org.motechproject.server.outbox; import org.motechproject.ivr.model.CallInitiationException; import org.motechproject.ivr.service.CallRequest; import org.motechproject.ivr.service.IVRService; import org.motechproject.outbox.api.EventKeys; import org.motechproject.scheduler.domain.CronJobId; import org.motechproject.scheduler.domain.CronSchedulableJob; import org.motechproject.scheduler.domain.MotechEvent; import org.motechproject.scheduler.gateway.MotechSchedulerGateway; import org.motechproject.server.event.annotations.MotechListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * */ public class OutboxExecutionHandler { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private MotechSchedulerGateway schedulerGateway; @Autowired private IVRService ivrService; @Autowired private Properties outboxProperties; @MotechListener(subjects = {EventKeys.EXECUTE_OUTBOX_SUBJECT }) public void execute(MotechEvent event) { String externalID = EventKeys.getExternalID(event); if (externalID == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.EXTERNAL_ID_KEY + " parameter"); return; } String phoneNumber = EventKeys.getPhoneNumberKey(event); if (phoneNumber == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.PHONE_NUMBER_KEY + " parameter"); return; } String language = EventKeys.getLanguageKey(event); if (language == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.LANGUAGE_KEY + " parameter"); return; } try { final int timeOut = 20000; String vxmlUrl = "http://" + outboxProperties.getProperty("outbox.host.ip") + "/motech-platform-server/module/outbox/vxml/outboxMessage?pId=" + externalID + "&ln=" + language; CallRequest callRequest = new CallRequest(phoneNumber, timeOut, vxmlUrl); Map<String, Object> messageParameters = new HashMap<String, Object>(); messageParameters.put(EventKeys.EXTERNAL_ID_KEY, externalID); MotechEvent incompleteEvent = new MotechEvent(EventKeys.INCOMPLETE_OUTBOX_CALL_SUBJECT, messageParameters); callRequest.setOnBusyEvent(incompleteEvent); callRequest.setOnFailureEvent(incompleteEvent); callRequest.setOnNoAnswerEvent(incompleteEvent); MotechEvent successEvent = new MotechEvent(EventKeys.COMPLETED_OUTBOX_CALL_SUBJECT, messageParameters); callRequest.setOnSuccessEvent(successEvent); ivrService.initiateCall(callRequest); } catch (CallInitiationException e) { logger.warn("Unable to initiate call to externalId=" + externalID + " e: " + e.getMessage()); } } @MotechListener(subjects = {EventKeys.SCHEDULE_EXECUTION_SUBJECT }) public void schedule(MotechEvent event) { Integer callHour = EventKeys.getCallHourKey(event); if (callHour == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.CALL_HOUR_KEY + " parameter"); return; } Integer callMinute = EventKeys.getCallMinuteKey(event); if (callMinute == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.CALL_MINUTE_KEY + " parameter"); return; } String externalID = EventKeys.getExternalID(event); if (externalID == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.EXTERNAL_ID_KEY + " parameter"); return; } String phoneNumber = EventKeys.getPhoneNumberKey(event); if (phoneNumber == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.PHONE_NUMBER_KEY + " parameter"); return; } MotechEvent reminderEvent = new MotechEvent(EventKeys.EXECUTE_OUTBOX_SUBJECT, event.getParameters()); CronSchedulableJob cronSchedulableJob = new CronSchedulableJob(reminderEvent, String.format("0 %d %d * * ?", callMinute, callHour)); schedulerGateway.scheduleJob(cronSchedulableJob); } @MotechListener(subjects = {EventKeys.UNSCHEDULE_EXECUTION_SUBJECT }) public void unschedule(MotechEvent event) { if (EventKeys.getScheduleJobIdKey(event) == null) { logger.error(String.format("Can not handle Event: %s. The event is invalid - missing the %s parameter", event.getSubject(), EventKeys.SCHEDULE_JOB_ID_KEY)); return; } schedulerGateway.unscheduleJob(new CronJobId(event)); } }
motech-outbox/src/main/java/org/motechproject/server/outbox/OutboxExecutionHandler.java
package org.motechproject.server.outbox; import org.motechproject.ivr.model.CallInitiationException; import org.motechproject.ivr.service.CallRequest; import org.motechproject.ivr.service.IVRService; import org.motechproject.outbox.api.EventKeys; import org.motechproject.scheduler.domain.CronJobId; import org.motechproject.scheduler.domain.CronSchedulableJob; import org.motechproject.scheduler.domain.JobId; import org.motechproject.scheduler.domain.MotechEvent; import org.motechproject.scheduler.gateway.MotechSchedulerGateway; import org.motechproject.server.event.annotations.MotechListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * */ public class OutboxExecutionHandler { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private MotechSchedulerGateway schedulerGateway; @Autowired private IVRService ivrService; @Autowired private Properties outboxProperties; @MotechListener(subjects = {EventKeys.EXECUTE_OUTBOX_SUBJECT }) public void execute(MotechEvent event) { String externalID = EventKeys.getExternalID(event); if (externalID == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.EXTERNAL_ID_KEY + " parameter"); return; } String phoneNumber = EventKeys.getPhoneNumberKey(event); if (phoneNumber == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.PHONE_NUMBER_KEY + " parameter"); return; } String language = EventKeys.getLanguageKey(event); if (language == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.LANGUAGE_KEY + " parameter"); return; } try { final int timeOut = 20000; String vxmlUrl = "http://" + outboxProperties.getProperty("outbox.host.ip") + "/motech-platform-server/module/outbox/vxml/outboxMessage?pId=" + externalID + "&ln=" + language; CallRequest callRequest = new CallRequest(phoneNumber, timeOut, vxmlUrl); Map<String, Object> messageParameters = new HashMap<String, Object>(); messageParameters.put(EventKeys.EXTERNAL_ID_KEY, externalID); MotechEvent incompleteEvent = new MotechEvent(EventKeys.INCOMPLETE_OUTBOX_CALL_SUBJECT, messageParameters); callRequest.setOnBusyEvent(incompleteEvent); callRequest.setOnFailureEvent(incompleteEvent); callRequest.setOnNoAnswerEvent(incompleteEvent); MotechEvent successEvent = new MotechEvent(EventKeys.COMPLETED_OUTBOX_CALL_SUBJECT, messageParameters); callRequest.setOnSuccessEvent(successEvent); ivrService.initiateCall(callRequest); } catch (CallInitiationException e) { logger.warn("Unable to initiate call to externalId=" + externalID + " e: " + e.getMessage()); } } @MotechListener(subjects = {EventKeys.SCHEDULE_EXECUTION_SUBJECT }) public void schedule(MotechEvent event) { Integer callHour = EventKeys.getCallHourKey(event); if (callHour == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.CALL_HOUR_KEY + " parameter"); return; } Integer callMinute = EventKeys.getCallMinuteKey(event); if (callMinute == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.CALL_MINUTE_KEY + " parameter"); return; } String externalID = EventKeys.getExternalID(event); if (externalID == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.EXTERNAL_ID_KEY + " parameter"); return; } String phoneNumber = EventKeys.getPhoneNumberKey(event); if (phoneNumber == null) { logger.error("Can not handle Event: " + event.getSubject() + ". The event is invalid - missing the " + EventKeys.PHONE_NUMBER_KEY + " parameter"); return; } MotechEvent reminderEvent = new MotechEvent(EventKeys.EXECUTE_OUTBOX_SUBJECT, event.getParameters()); CronSchedulableJob cronSchedulableJob = new CronSchedulableJob(reminderEvent, String.format("0 %d %d * * ?", callMinute, callHour)); schedulerGateway.scheduleJob(cronSchedulableJob); } @MotechListener(subjects = {EventKeys.UNSCHEDULE_EXECUTION_SUBJECT }) public void unschedule(MotechEvent event) { if (EventKeys.getScheduleJobIdKey(event) == null) { logger.error(String.format("Can not handle Event: %s. The event is invalid - missing the %s parameter", event.getSubject(), EventKeys.SCHEDULE_JOB_ID_KEY)); return; } schedulerGateway.unscheduleJob(new CronJobId(event)); } }
Soham | 0113 | Fixed checkstyle warnings in motech-outbox Change-Id: Id991ac7f25ae29d9c3989a6b82386389c61bd5cb
motech-outbox/src/main/java/org/motechproject/server/outbox/OutboxExecutionHandler.java
Soham | 0113 | Fixed checkstyle warnings in motech-outbox
Java
isc
483b278cf0330486be5d157080bbcef7172e40b4
0
plues/model-generator,plues/model-generator
package de.hhu.stups.plues.modelgenerator; import de.hhu.stups.plues.data.Store; import de.hhu.stups.plues.modelgenerator.twig.HelperExtension; import org.jtwig.JtwigModel; import org.jtwig.JtwigTemplate; import org.jtwig.environment.EnvironmentConfiguration; import org.jtwig.environment.EnvironmentConfigurationBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Renderer { private final Logger logger = LoggerFactory.getLogger(getClass()); private static final EnvironmentConfiguration config = EnvironmentConfigurationBuilder .configuration().extensions().add(new HelperExtension()).and() .render().withOutputCharset(Charset.forName("utf8")) .and().build(); private final Store store; public Renderer(final Store db) { this.store = db; } @SuppressWarnings("WeakerAccess") protected JtwigTemplate loadTemplateFromResource(final String path) { return JtwigTemplate.classpathTemplate(path, config); } @SuppressWarnings("WeakerAccess") protected JtwigTemplate loadTemplate(final String path) { final String tmpl = new File(path).getAbsolutePath(); return JtwigTemplate.fileTemplate(tmpl, config); } @SuppressWarnings("WeakerAccess") protected JtwigTemplate loadTemplate(final FileType tp) { final String template = tp.template; logger.info("Using template: " + template); return this.loadTemplateFromResource(template); } @SuppressWarnings("WeakerAccess") public ByteArrayOutputStream renderWith(final String path) { final JtwigTemplate template = loadTemplate(path); return this.render(template); } @SuppressWarnings("WeakerAccess") public void renderWith(final String path, final File out) { final JtwigTemplate template = loadTemplate(path); this.render(template, out); } @SuppressWarnings("WeakerAccess") public ByteArrayOutputStream renderFor(final FileType tp) { final JtwigTemplate template = loadTemplate(tp); return this.render(template); } public void renderFor(final FileType tp, final File out) { final JtwigTemplate template = loadTemplate(tp); this.render(template, out); } @SuppressWarnings("WeakerAccess") protected ByteArrayOutputStream render(final JtwigTemplate template) { final JtwigModel model = geModel(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); template.render(model, out); return out; } @SuppressWarnings("WeakerAccess") protected void render(final JtwigTemplate template, final File out) { final JtwigModel model = geModel(); try (FileOutputStream fos = new FileOutputStream(out)) { try (BufferedOutputStream bos = new BufferedOutputStream(fos)) { template.render(model, bos); } } catch (final IOException exception) { logger.error("Exception writing template", exception); } } private JtwigModel geModel() { final LocalDateTime date = LocalDateTime.now(); final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; final String formattedDate = date.format(formatter); return JtwigModel.newModel() .with("date", formattedDate) .with("info", store.getInfo()) .with("short_name", store.getInfoByKey("short-name")) .with("abstract_units", store.getAbstractUnits()) .with("courses", store.getCourses()) .with("module_levels", store.getModuleLevels()) .with("groups", store.getGroups()) .with("levels", store.getLevels()) .with("modules", store.getModules()) .with("module_abstract_unit_semester", store.getModuleAbstractUnitSemester()) .with("module_abstract_unit_type", store.getModuleAbstractUnitType()) .with("sessions", store.getSessions()) .with("units", store.getUnits()); } }
src/main/java/de/hhu/stups/plues/modelgenerator/Renderer.java
package de.hhu.stups.plues.modelgenerator; import de.hhu.stups.plues.data.Store; import de.hhu.stups.plues.modelgenerator.twig.HelperExtension; import org.jtwig.JtwigModel; import org.jtwig.JtwigTemplate; import org.jtwig.environment.EnvironmentConfiguration; import org.jtwig.environment.EnvironmentConfigurationBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.Date; public class Renderer { private final Logger logger = LoggerFactory.getLogger(getClass()); private static final EnvironmentConfiguration config = EnvironmentConfigurationBuilder .configuration().extensions().add(new HelperExtension()).and() .render().withOutputCharset(Charset.forName("utf8")) .and().build(); private final Store store; public Renderer(final Store db) { this.store = db; } @SuppressWarnings("WeakerAccess") protected JtwigTemplate loadTemplateFromResource(final String path) { return JtwigTemplate.classpathTemplate(path, config); } @SuppressWarnings("WeakerAccess") protected JtwigTemplate loadTemplate(final String path) { final String tmpl = new File(path).getAbsolutePath(); return JtwigTemplate.fileTemplate(tmpl, config); } @SuppressWarnings("WeakerAccess") protected JtwigTemplate loadTemplate(final FileType tp) { final String template = tp.template; logger.info("Using template: " + template); return this.loadTemplateFromResource(template); } @SuppressWarnings("WeakerAccess") public ByteArrayOutputStream renderWith(final String path) { final JtwigTemplate template = loadTemplate(path); return this.render(template); } @SuppressWarnings("WeakerAccess") public void renderWith(final String path, final File out) { final JtwigTemplate template = loadTemplate(path); this.render(template, out); } @SuppressWarnings("WeakerAccess") public ByteArrayOutputStream renderFor(final FileType tp) { final JtwigTemplate template = loadTemplate(tp); return this.render(template); } public void renderFor(final FileType tp, final File out) { final JtwigTemplate template = loadTemplate(tp); this.render(template, out); } @SuppressWarnings("WeakerAccess") protected ByteArrayOutputStream render(final JtwigTemplate template) { final JtwigModel model = geModel(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); template.render(model, out); return out; } @SuppressWarnings("WeakerAccess") protected void render(final JtwigTemplate template, final File out) { final JtwigModel model = geModel(); try (FileOutputStream fos = new FileOutputStream(out)) { try (BufferedOutputStream bos = new BufferedOutputStream(fos)) { template.render(model, bos); } } catch (final IOException exception) { logger.error("Exception writing template", exception); } } private JtwigModel geModel() { return JtwigModel.newModel() .with("date", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX") .format(new Date())) .with("info", store.getInfo()) .with("short_name", store.getInfoByKey("short-name")) .with("abstract_units", store.getAbstractUnits()) .with("courses", store.getCourses()) .with("module_levels", store.getModuleLevels()) .with("groups", store.getGroups()) .with("levels", store.getLevels()) .with("modules", store.getModules()) .with("module_abstract_unit_semester", store.getModuleAbstractUnitSemester()) .with("module_abstract_unit_type", store.getModuleAbstractUnitType()) .with("sessions", store.getSessions()) .with("units", store.getUnits()); } }
Use LocalDateTime to create a date string for rendering
src/main/java/de/hhu/stups/plues/modelgenerator/Renderer.java
Use LocalDateTime to create a date string for rendering
Java
mit
685d74cc028c80392adc9afbadb573ffc30f2119
0
dchouzer/OOGASalad,tjqadri101/oogasalad
package stage; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import objects.GameObject; import objects.NonPlayer; import saladConstants.SaladConstants; import util.AttributeMaker; /** * @author Main Justin (Zihao) Zhang * @contribution David Chou */ public class Level { protected Map<Integer, Scene> mySceneMap; protected int myID; protected Scene myInitialScene; protected String myEventBehavior; private ArrayList<Object> myEventParameters; public Level(int id) { myID = id; mySceneMap = new HashMap<Integer, Scene>(); } public int getID(){ return myID; } public void resetID(int id){ myID = id; } public void setInitialScene(int sceneID){ if(!mySceneMap.containsKey(sceneID)) return; myInitialScene = mySceneMap.get(sceneID); } public Scene getInitialScene(){ return myInitialScene; } public void addScene(int sceneID) { Scene scene = new Scene(sceneID); mySceneMap.put(sceneID, scene); } public void addScene(int sceneID, Scene scene){ mySceneMap.put(sceneID, scene); } public void addNonPlayer(int sceneID, NonPlayer object) { mySceneMap.get(sceneID).addNonPlayer(object); } public NonPlayer getNonPlayer(int sceneID, int objectID) { return mySceneMap.get(sceneID).getNonPlayer(objectID); } public Scene getScene(int sceneID){ return mySceneMap.get(sceneID); } public void removeScene(int sceneID) { mySceneMap.remove(sceneID); } public void setEventBehavior(String type, Object ... args){ myEventBehavior = type; myEventParameters = new ArrayList<Object>(); for(int i = 0; i < args.length; i ++){ myEventParameters.add(args[i]); } } public String getEventBehavior() { return myEventBehavior; } public List<Object> getEventParameters(){ return myEventParameters; } public List<GameObject> getObjectsByColid(int colid){ List<GameObject> objects = new ArrayList<GameObject>(); for(int sceneID: mySceneMap.keySet()){ Scene scene = mySceneMap.get(sceneID); objects.addAll(scene.getObjectsByColid(colid)); } return objects; } public List<String> getAttributes() { List<String> answer = new ArrayList<String>(); answer.add(AttributeMaker.addAttribute(SaladConstants.CREATE_LEVEL, SaladConstants.ID, myID)); for(int a: mySceneMap.keySet()){ List<String> sceneAttribute = mySceneMap.get(a).getAttributes(); String attribute = AttributeMaker.addAttribute(SaladConstants.SWITCH_SCENE, SaladConstants.ID, myID, SaladConstants.ID, false, mySceneMap.get(a).getID()); sceneAttribute.add(1, attribute); answer.addAll(sceneAttribute); } return answer; } /* @Siyang: * The following getter added to facilitate testing. */ public Map<Integer, Scene> getMySceneMap(){ return mySceneMap; } }
src/stage/Level.java
package stage; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import objects.GameObject; import objects.NonPlayer; import saladConstants.SaladConstants; import util.AttributeMaker; /** * @author Main Justin (Zihao) Zhang * @contribution David Chou */ public class Level { protected Map<Integer, Scene> mySceneMap; protected int myID; protected String myWinBehavior; protected List<Object> myWinParameters; protected String myEventBehavior; private ArrayList<Object> myEventParameters; public Level(int id) { myID = id; mySceneMap = new HashMap<Integer, Scene>(); } public int getID(){ return myID; } public void resetID(int id){ myID = id; } public void addScene(int sceneID) { Scene scene = new Scene(sceneID); mySceneMap.put(sceneID, scene); } public void addScene(int sceneID, Scene scene){ mySceneMap.put(sceneID, scene); } public void addNonPlayer(int sceneID, NonPlayer object) { mySceneMap.get(sceneID).addNonPlayer(object); } public NonPlayer getNonPlayer(int sceneID, int objectID) { return mySceneMap.get(sceneID).getNonPlayer(objectID); } public Scene getScene(int sceneID){ return mySceneMap.get(sceneID); } public void removeScene(int sceneID) { mySceneMap.remove(sceneID); } public void setEventBehavior(String type, Object ... args){ myEventBehavior = type; myEventParameters = new ArrayList<Object>(); for(int i = 0; i < args.length; i ++){ myEventParameters.add(args[i]); } } public String getEventBehavior() { return myEventBehavior; } public List<Object> getEventParameters(){ return myEventParameters; } public List<GameObject> getObjectsByColid(int colid){ List<GameObject> objects = new ArrayList<GameObject>(); for(int sceneID: mySceneMap.keySet()){ Scene scene = mySceneMap.get(sceneID); objects.addAll(scene.getObjectsByColid(colid)); } return objects; } public List<String> getAttributes() { List<String> answer = new ArrayList<String>(); answer.add(AttributeMaker.addAttribute(SaladConstants.CREATE_LEVEL, SaladConstants.ID, myID)); for(int a: mySceneMap.keySet()){ List<String> sceneAttribute = mySceneMap.get(a).getAttributes(); String attribute = AttributeMaker.addAttribute(SaladConstants.SWITCH_SCENE, SaladConstants.ID, myID, SaladConstants.ID, false, mySceneMap.get(a).getID()); sceneAttribute.add(1, attribute); answer.addAll(sceneAttribute); } answer.add(AttributeMaker.addAttribute(SaladConstants.CREATE_GOAL, myWinBehavior, true, myWinParameters)); return answer; } /* @Siyang: * The following getter added to facilitate testing. */ public Map<Integer, Scene> getMySceneMap(){ return mySceneMap; } }
update
src/stage/Level.java
update
Java
mit
465f73b14b9c9d416183c01cc5bb05c47d6e515f
0
Team4761/2016-Robot-Code
package org.robockets.stronghold.robot.commands; import org.robockets.stronghold.robot.highgoalshooter.MoveHood; import org.robockets.stronghold.robot.highgoalshooter.MoveTurnTable; import org.robockets.stronghold.robot.intake.IntakesUp; import edu.wpi.first.wpilibj.command.CommandGroup; /** * Moves the robot into the position for driving around, shooting, and intaking ball */ public class DrivePosition extends CommandGroup { public DrivePosition() { addSequential(new MoveHood(-70)); addSequential(new IntakesUp()); addSequential(new MoveTurnTable(0)); } }
src/org/robockets/stronghold/robot/commands/DrivePosition.java
package org.robockets.stronghold.robot.commands; import org.robockets.stronghold.robot.highgoalshooter.MoveHood; import org.robockets.stronghold.robot.highgoalshooter.MoveTurnTable; import org.robockets.stronghold.robot.intake.IntakesUp; import edu.wpi.first.wpilibj.command.CommandGroup; /** * */ public class DrivePosition extends CommandGroup { public DrivePosition() { addSequential(new MoveHood(-70)); addSequential(new IntakesUp()); addSequential(new MoveTurnTable(0)); } }
Add javadocs for drive position
src/org/robockets/stronghold/robot/commands/DrivePosition.java
Add javadocs for drive position
Java
mit
635e6f51a1d3642b6a238e8d7b598a3df2f29c63
0
Lwissitoon/Java_Lab
public class HolaMundo{ public static void main(String [] args){ System.out.println("Hola Mundo"); //1000260660_LUIS_MATEO_HOOTSUITE //100267532 - Bryan GUZMAN - Facebook } }
HolaMundo.java
public class HolaMundo{ public static void main(String [] args){ System.out.println("Hola Mundo"); //1000260660_LUIS_MATEO_HOOTSUITE } }
commit add a simple commit
HolaMundo.java
commit
Java
mit
e013a65eb543ee80648660b3cfc01267bcca5c4d
0
testcontainers/testcontainers-java,testcontainers/testcontainers-java,testcontainers/testcontainers-java
package org.testcontainers.containers; import com.google.common.collect.ImmutableMap; import org.apache.kafka.clients.admin.AdminClient; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.junit.Test; import org.rnorth.ducttape.unreliables.Unreliables; import org.testcontainers.Testcontainers; import org.testcontainers.utility.DockerImageName; import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.UUID; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; public class KafkaContainerTest { private static final DockerImageName KAFKA_TEST_IMAGE = DockerImageName.parse("confluentinc/cp-kafka:6.2.1"); private static final DockerImageName ZOOKEEPER_TEST_IMAGE = DockerImageName.parse( "confluentinc/cp-zookeeper:4.0.0" ); @Test public void testUsage() throws Exception { try (KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE)) { kafka.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } @Test public void testUsageWithSpecificImage() throws Exception { try ( // constructorWithVersion { KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:6.2.1")) // } ) { kafka.start(); testKafkaFunctionality( // getBootstrapServers { kafka.getBootstrapServers() // } ); } } @Test public void testUsageWithVersion() throws Exception { try (KafkaContainer kafka = new KafkaContainer("6.2.1")) { kafka.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } @Test public void testExternalZookeeperWithExternalNetwork() throws Exception { try ( Network network = Network.newNetwork(); // withExternalZookeeper { KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE) .withNetwork(network) .withExternalZookeeper("zookeeper:2181"); // } GenericContainer<?> zookeeper = new GenericContainer<>(ZOOKEEPER_TEST_IMAGE) .withNetwork(network) .withNetworkAliases("zookeeper") .withEnv("ZOOKEEPER_CLIENT_PORT", "2181"); // withKafkaNetwork { GenericContainer<?> application = new GenericContainer<>(DockerImageName.parse("alpine")) .withNetwork(network) // } .withNetworkAliases("dummy") .withCommand("sleep 10000") ) { zookeeper.start(); kafka.start(); application.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } @Test public void testConfluentPlatformVersion7() throws Exception { try (KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:7.2.2"))) { kafka.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } @Test public void testConfluentPlatformVersion5() throws Exception { try (KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:5.4.3"))) { kafka.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } @Test public void testWithHostExposedPort() throws Exception { Testcontainers.exposeHostPorts(12345); try (KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE)) { kafka.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } @Test public void testWithHostExposedPortAndExternalNetwork() throws Exception { Testcontainers.exposeHostPorts(12345); try (KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE).withNetwork(Network.newNetwork())) { kafka.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } protected void testKafkaFunctionality(String bootstrapServers) throws Exception { testKafkaFunctionality(bootstrapServers, 1, 1); } protected void testKafkaFunctionality(String bootstrapServers, int partitions, int rf) throws Exception { try ( AdminClient adminClient = AdminClient.create( ImmutableMap.of(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers) ); KafkaProducer<String, String> producer = new KafkaProducer<>( ImmutableMap.of( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers, ProducerConfig.CLIENT_ID_CONFIG, UUID.randomUUID().toString() ), new StringSerializer(), new StringSerializer() ); KafkaConsumer<String, String> consumer = new KafkaConsumer<>( ImmutableMap.of( ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers, ConsumerConfig.GROUP_ID_CONFIG, "tc-" + UUID.randomUUID(), ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest" ), new StringDeserializer(), new StringDeserializer() ); ) { String topicName = "messages-" + UUID.randomUUID(); Collection<NewTopic> topics = Collections.singletonList(new NewTopic(topicName, partitions, (short) rf)); adminClient.createTopics(topics).all().get(30, TimeUnit.SECONDS); consumer.subscribe(Collections.singletonList(topicName)); producer.send(new ProducerRecord<>(topicName, "testcontainers", "rulezzz")).get(); Unreliables.retryUntilTrue( 10, TimeUnit.SECONDS, () -> { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100)); if (records.isEmpty()) { return false; } assertThat(records) .hasSize(1) .extracting(ConsumerRecord::topic, ConsumerRecord::key, ConsumerRecord::value) .containsExactly(tuple(topicName, "testcontainers", "rulezzz")); return true; } ); consumer.unsubscribe(); } } }
modules/kafka/src/test/java/org/testcontainers/containers/KafkaContainerTest.java
package org.testcontainers.containers; import com.google.common.collect.ImmutableMap; import org.apache.kafka.clients.admin.AdminClient; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.junit.Test; import org.rnorth.ducttape.unreliables.Unreliables; import org.testcontainers.Testcontainers; import org.testcontainers.utility.DockerImageName; import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.UUID; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; public class KafkaContainerTest { private static final DockerImageName KAFKA_TEST_IMAGE = DockerImageName.parse("confluentinc/cp-kafka:6.2.1"); private static final DockerImageName ZOOKEEPER_TEST_IMAGE = DockerImageName.parse( "confluentinc/cp-zookeeper:4.0.0" ); @Test public void testUsage() throws Exception { try (KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE)) { kafka.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } @Test public void testUsageWithSpecificImage() throws Exception { try ( // constructorWithVersion { KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:6.2.1")) // } ) { kafka.start(); testKafkaFunctionality( // getBootstrapServers { kafka.getBootstrapServers() // } ); } } @Test public void testUsageWithVersion() throws Exception { try (KafkaContainer kafka = new KafkaContainer("6.2.1")) { kafka.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } @Test public void testExternalZookeeperWithExternalNetwork() throws Exception { try ( Network network = Network.newNetwork(); // withExternalZookeeper { KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE) .withNetwork(network) .withExternalZookeeper("zookeeper:2181"); // } GenericContainer<?> zookeeper = new GenericContainer<>(ZOOKEEPER_TEST_IMAGE) .withNetwork(network) .withNetworkAliases("zookeeper") .withEnv("ZOOKEEPER_CLIENT_PORT", "2181"); // withKafkaNetwork { GenericContainer<?> application = new GenericContainer<>(DockerImageName.parse("alpine")) .withNetwork(network) // } .withNetworkAliases("dummy") .withCommand("sleep 10000") ) { zookeeper.start(); kafka.start(); application.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } @Test public void testConfluentPlatformVersion5() throws Exception { try (KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:5.4.3"))) { kafka.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } @Test public void testWithHostExposedPort() throws Exception { Testcontainers.exposeHostPorts(12345); try (KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE)) { kafka.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } @Test public void testWithHostExposedPortAndExternalNetwork() throws Exception { Testcontainers.exposeHostPorts(12345); try (KafkaContainer kafka = new KafkaContainer(KAFKA_TEST_IMAGE).withNetwork(Network.newNetwork())) { kafka.start(); testKafkaFunctionality(kafka.getBootstrapServers()); } } protected void testKafkaFunctionality(String bootstrapServers) throws Exception { testKafkaFunctionality(bootstrapServers, 1, 1); } protected void testKafkaFunctionality(String bootstrapServers, int partitions, int rf) throws Exception { try ( AdminClient adminClient = AdminClient.create( ImmutableMap.of(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers) ); KafkaProducer<String, String> producer = new KafkaProducer<>( ImmutableMap.of( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers, ProducerConfig.CLIENT_ID_CONFIG, UUID.randomUUID().toString() ), new StringSerializer(), new StringSerializer() ); KafkaConsumer<String, String> consumer = new KafkaConsumer<>( ImmutableMap.of( ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers, ConsumerConfig.GROUP_ID_CONFIG, "tc-" + UUID.randomUUID(), ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest" ), new StringDeserializer(), new StringDeserializer() ); ) { String topicName = "messages-" + UUID.randomUUID(); Collection<NewTopic> topics = Collections.singletonList(new NewTopic(topicName, partitions, (short) rf)); adminClient.createTopics(topics).all().get(30, TimeUnit.SECONDS); consumer.subscribe(Collections.singletonList(topicName)); producer.send(new ProducerRecord<>(topicName, "testcontainers", "rulezzz")).get(); Unreliables.retryUntilTrue( 10, TimeUnit.SECONDS, () -> { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100)); if (records.isEmpty()) { return false; } assertThat(records) .hasSize(1) .extracting(ConsumerRecord::topic, ConsumerRecord::key, ConsumerRecord::value) .containsExactly(tuple(topicName, "testcontainers", "rulezzz")); return true; } ); consumer.unsubscribe(); } } }
Add test for Confluent platform version 7 to `KafkaContainerTest` (#5989)
modules/kafka/src/test/java/org/testcontainers/containers/KafkaContainerTest.java
Add test for Confluent platform version 7 to `KafkaContainerTest` (#5989)
Java
mit
f270fce993681c1480b638bdd6d90e3818751ccb
0
SilentChaos512/ScalingHealth
package net.silentchaos512.scalinghealth.network.message; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.silentchaos512.lib.event.ClientTicks; import net.silentchaos512.scalinghealth.ScalingHealth; import net.silentchaos512.scalinghealth.config.Config; import net.silentchaos512.scalinghealth.network.Message; import net.silentchaos512.scalinghealth.utils.ModifierHandler; import net.silentchaos512.scalinghealth.utils.SHPlayerDataHandler; import net.silentchaos512.scalinghealth.utils.SHPlayerDataHandler.PlayerData; import javax.annotation.Nullable; @SuppressWarnings("WeakerAccess") public class MessageDataSync extends Message { public NBTTagCompound tags; public String playerName; public int experienceLevel; @SuppressWarnings("unused") public MessageDataSync() {} public MessageDataSync(PlayerData data, EntityPlayer player) { tags = new NBTTagCompound(); data.writeToNBT(tags); this.playerName = player.getName(); this.experienceLevel = player.experienceLevel; } @Override @Nullable @SideOnly(Side.CLIENT) public IMessage handleMessage(MessageContext context) { ClientTicks.scheduleAction(() -> { EntityPlayer player = getPlayerByName(playerName); if (player != null) { PlayerData data = SHPlayerDataHandler.get(player); if (data != null) { data.readFromNBT(tags); // Set players health and max health. if (Config.Player.Health.allowModify) { ModifierHandler.setMaxHealth(player, data.getMaxHealth(), 0); if (data.getHealth() > 0f) player.setHealth(data.getHealth()); } } player.experienceLevel = experienceLevel; } }); return null; } @Nullable private static EntityPlayer getPlayerByName(String name) { EntityPlayer localPlayer = ScalingHealth.proxy.getClientPlayer(); if (localPlayer != null) { World world = localPlayer.world; if (world != null) { return world.getPlayerEntityByName(name); } } return null; } }
src/main/java/net/silentchaos512/scalinghealth/network/message/MessageDataSync.java
package net.silentchaos512.scalinghealth.network.message; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.silentchaos512.lib.event.ClientTicks; import net.silentchaos512.scalinghealth.ScalingHealth; import net.silentchaos512.scalinghealth.config.Config; import net.silentchaos512.scalinghealth.network.Message; import net.silentchaos512.scalinghealth.utils.ModifierHandler; import net.silentchaos512.scalinghealth.utils.SHPlayerDataHandler; import net.silentchaos512.scalinghealth.utils.SHPlayerDataHandler.PlayerData; import javax.annotation.Nullable; @SuppressWarnings("WeakerAccess") public class MessageDataSync extends Message { public NBTTagCompound tags; public String playerName; public int experienceLevel; @SuppressWarnings("unused") public MessageDataSync() {} public MessageDataSync(PlayerData data, EntityPlayer player) { tags = new NBTTagCompound(); data.writeToNBT(tags); this.playerName = player.getName(); this.experienceLevel = player.experienceLevel; } @Override @Nullable @SideOnly(Side.CLIENT) public IMessage handleMessage(MessageContext context) { ClientTicks.scheduleAction(() -> { EntityPlayer player = ScalingHealth.proxy.getClientPlayer().world.getPlayerEntityByName(playerName); if (player != null) { PlayerData data = SHPlayerDataHandler.get(player); if (data != null) { data.readFromNBT(tags); // Set players health and max health. if (Config.Player.Health.allowModify) { ModifierHandler.setMaxHealth(player, data.getMaxHealth(), 0); if (data.getHealth() > 0f) player.setHealth(data.getHealth()); } } player.experienceLevel = experienceLevel; } }); return null; } }
Should fix #141
src/main/java/net/silentchaos512/scalinghealth/network/message/MessageDataSync.java
Should fix #141
Java
agpl-3.0
377b47a9ad30f4867701173424b4de86d38e876a
0
cxxly/cstack,cxxly/cstack,cxxly/cstack,cxxly/cstack,cxxly/cstack,cxxly/cstack
/* * LICENCE : CloudUnit is available under the GNU Affero General Public License : https://gnu.org/licenses/agpl.html * but CloudUnit is licensed too under a standard commercial license. * Please contact our sales team if you would like to discuss the specifics of our Enterprise license. * If you are not sure whether the AGPL is right for you, * you can always test our software under the AGPL and inspect the source code before you contact us * about purchasing a commercial license. * * LEGAL TERMS : "CloudUnit" is a registered trademark of Treeptik and can't be used to endorse * or promote products derived from this project without prior written permission from Treeptik. * Products or services derived from this software may not be called "CloudUnit" * nor may "Treeptik" or similar confusing terms appear in their names without prior written permission. * For any questions, contact us : contact@treeptik.fr */ package cn.org.once.cstack.controller; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.org.once.cstack.service.MonitoringService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import cn.org.once.cstack.exception.CheckException; import cn.org.once.cstack.exception.ServiceException; import cn.org.once.cstack.model.Metric; import cn.org.once.cstack.service.DockerService; /** * Created by nicolas on 25/08/2014. */ @RestController @RequestMapping("/monitoring") public class MonitoringController { private Logger logger = LoggerFactory.getLogger(MonitoringController.class); @Inject private MonitoringService monitoringService; @Inject private DockerService dockerService; /** * Is a wrapper to cAdvisor API * * @return * @throws ServiceException * @throws CheckException */ @RequestMapping(value = "/api/machine", method = RequestMethod.GET) public void infoMachine(HttpServletRequest request, HttpServletResponse response) throws ServiceException, CheckException { String responseFromCAdvisor = monitoringService.getJsonMachineFromCAdvisor(); try { response.getWriter().write(responseFromCAdvisor); response.flushBuffer(); } catch (Exception e) { logger.error("error during write and flush response", responseFromCAdvisor); } } /** * * Is a wrapper to cAdvisor API * * @param containerName * @throws ServiceException * @throws CheckException */ @RequestMapping(value = "/api/containers/docker/{containerName}", method = RequestMethod.GET) public void infoContainer(HttpServletRequest request, HttpServletResponse response, @PathVariable String containerName) throws ServiceException, CheckException { try { String containerId = dockerService.getContainerId(containerName); String responseFromCAdvisor = monitoringService.getJsonFromCAdvisor(containerId); if (logger.isDebugEnabled()) { logger.debug("containerId=" + containerId); logger.debug("responseFromCAdvisor=" + responseFromCAdvisor); } response.getWriter().write(responseFromCAdvisor); response.flushBuffer(); } catch (Exception e) { logger.error("error during write and flush response", containerName); } } @RequestMapping(value = "/metrics/{serverName}") public List<Metric> findAllByServer(@PathVariable("serverName") String serverName) { return monitoringService.findByServer(serverName); } /** * Return the position into the architecture of the service * @return */ @RequestMapping("/location") public ResponseEntity<String> getServiceLocation(@Value("${kibana.domain:kibana.cloudunit.dev}") String location) { if (location != null && !location.startsWith("https")) { location = "https://" + location; } return ResponseEntity.ok(location); } }
cu-manager/src/main/java/cn/org/once/cstack/controller/MonitoringController.java
/* * LICENCE : CloudUnit is available under the GNU Affero General Public License : https://gnu.org/licenses/agpl.html * but CloudUnit is licensed too under a standard commercial license. * Please contact our sales team if you would like to discuss the specifics of our Enterprise license. * If you are not sure whether the AGPL is right for you, * you can always test our software under the AGPL and inspect the source code before you contact us * about purchasing a commercial license. * * LEGAL TERMS : "CloudUnit" is a registered trademark of Treeptik and can't be used to endorse * or promote products derived from this project without prior written permission from Treeptik. * Products or services derived from this software may not be called "CloudUnit" * nor may "Treeptik" or similar confusing terms appear in their names without prior written permission. * For any questions, contact us : contact@treeptik.fr */ package cn.org.once.cstack.controller; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.org.once.cstack.service.MonitoringService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import cn.org.once.cstack.exception.CheckException; import cn.org.once.cstack.exception.ServiceException; import cn.org.once.cstack.model.Metric; import cn.org.once.cstack.service.DockerService; /** * Created by nicolas on 25/08/2014. */ @RestController @RequestMapping("/monitoring") public class MonitoringController { private Logger logger = LoggerFactory.getLogger(MonitoringController.class); @Inject private MonitoringService monitoringService; @Inject private DockerService dockerService; /** * Is a wrapper to cAdvisor API * * @return * @throws ServiceException * @throws CheckException */ @RequestMapping(value = "/api/machine", method = RequestMethod.GET) public void infoMachine(HttpServletRequest request, HttpServletResponse response) throws ServiceException, CheckException { String responseFromCAdvisor = monitoringService.getJsonMachineFromCAdvisor(); try { response.getWriter().write(responseFromCAdvisor); response.flushBuffer(); } catch (Exception e) { logger.error("error during write and flush response", responseFromCAdvisor); } } /** * * Is a wrapper to cAdvisor API * * @param containerName * @throws ServiceException * @throws CheckException */ @RequestMapping(value = "/api/containers/docker/{containerName}", method = RequestMethod.GET) public void infoContainer(HttpServletRequest request, HttpServletResponse response, @PathVariable String containerName) throws ServiceException, CheckException { try { String containerId = dockerService.getContainerId(containerName); String responseFromCAdvisor = monitoringService.getJsonFromCAdvisor(containerId); if (logger.isDebugEnabled()) { logger.debug("containerId=" + containerId); logger.debug("responseFromCAdvisor=" + responseFromCAdvisor); } response.getWriter().write(responseFromCAdvisor); response.flushBuffer(); } catch (Exception e) { logger.error("error during write and flush response", containerName); } } @RequestMapping(value = "/metrics/{serverName}") public List<Metric> findAllByServer(@PathVariable("serverName") String serverName) { return monitoringService.findByServer(serverName); } /** * Return the position into the architecture of the service * @return */ @RequestMapping("/location") public ResponseEntity<String> getServiceLocation(@Value("${kibana.domain : kibana.cloudunit.dev}") String location) { if (location != null && !location.startsWith("https")) { location = "https://" + location; } return ResponseEntity.ok(location); } }
fix monitor url bug.
cu-manager/src/main/java/cn/org/once/cstack/controller/MonitoringController.java
fix monitor url bug.
Java
lgpl-2.1
bbe5a2366e02cff6050a39cf149255f6356c45aa
0
romani/checkstyle,rnveach/checkstyle,romani/checkstyle,checkstyle/checkstyle,rnveach/checkstyle,romani/checkstyle,romani/checkstyle,checkstyle/checkstyle,romani/checkstyle,checkstyle/checkstyle,checkstyle/checkstyle,checkstyle/checkstyle,romani/checkstyle,rnveach/checkstyle,rnveach/checkstyle,checkstyle/checkstyle,rnveach/checkstyle,rnveach/checkstyle
//non-compiled with javac: contains different class name by demand of test package com.puppycrawl.tools.checkstyle.checks.outertypefilename; /* Config: * default */ public record IncorrectName1(int x, int y, String str) { // violation }
src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/outertypefilename/InputOuterTypeFilenameRecord.java
//non-compiled with javac: contains different class name by demand of test package com.puppycrawl.tools.checkstyle.checks.outertypefilename; /* Config: * default */ public record IncorrectName(int x, int y, String str) { // violation }
minor: rename IncorrectName to IncorrectName1 for OuterTypeFilenameCheck for updated UT(#8598)
src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/outertypefilename/InputOuterTypeFilenameRecord.java
minor: rename IncorrectName to IncorrectName1 for OuterTypeFilenameCheck for updated UT(#8598)
Java
apache-2.0
14e0168b845a3d6ef8f44f29698d3bccade40b5a
0
marschall/undertow,jamezp/undertow,amannm/undertow,grassjedi/undertow,baranowb/undertow,soul2zimate/undertow,jasonchaffee/undertow,grassjedi/undertow,pferraro/undertow,wildfly-security-incubator/undertow,golovnin/undertow,darranl/undertow,aradchykov/undertow,TomasHofman/undertow,pferraro/undertow,jasonchaffee/undertow,ctomc/undertow,popstr/undertow,amannm/undertow,rogerchina/undertow,stuartwdouglas/undertow,marschall/undertow,rhusar/undertow,Karm/undertow,undertow-io/undertow,pferraro/undertow,n1hility/undertow,pedroigor/undertow,nkhuyu/undertow,soul2zimate/undertow,popstr/undertow,biddyweb/undertow,baranowb/undertow,n1hility/undertow,n1hility/undertow,undertow-io/undertow,ctomc/undertow,rhatlapa/undertow,ctomc/undertow,jamezp/undertow,rhatlapa/undertow,wildfly-security-incubator/undertow,grassjedi/undertow,darranl/undertow,yonglehou/undertow,jstourac/undertow,nkhuyu/undertow,golovnin/undertow,aldaris/undertow,Karm/undertow,aradchykov/undertow,rogerchina/undertow,aldaris/undertow,undertow-io/undertow,rhusar/undertow,jstourac/undertow,yonglehou/undertow,aradchykov/undertow,nkhuyu/undertow,jstourac/undertow,stuartwdouglas/undertow,amannm/undertow,pedroigor/undertow,Karm/undertow,jasonchaffee/undertow,wildfly-security-incubator/undertow,popstr/undertow,jamezp/undertow,baranowb/undertow,yonglehou/undertow,marschall/undertow,biddyweb/undertow,rogerchina/undertow,darranl/undertow,stuartwdouglas/undertow,rhatlapa/undertow,TomasHofman/undertow,msfm/undertow,biddyweb/undertow,golovnin/undertow,msfm/undertow,msfm/undertow,TomasHofman/undertow,aldaris/undertow,rhusar/undertow,soul2zimate/undertow,pedroigor/undertow
package io.undertow.server.handlers.proxy; import io.undertow.Undertow; import io.undertow.UndertowOptions; import io.undertow.protocols.ssl.UndertowXnioSsl; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.ResponseCodeHandler; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpOneOnly; import io.undertow.testutils.ProxyIgnore; import io.undertow.testutils.TestHttpClient; import io.undertow.util.Headers; import io.undertow.util.StatusCodes; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.xnio.OptionMap; import org.xnio.Options; import java.net.URI; import static io.undertow.Handlers.jvmRoute; import static io.undertow.Handlers.path; /** * Created by ivannagy on 8/26/14. */ @RunWith(DefaultServer.class) @HttpOneOnly @ProxyIgnore public class ProxyHandlerXForwardedForTestCase { protected static Undertow server; protected static int port; protected static int sslPort; protected static int handlerPort; protected static UndertowXnioSsl ssl; @BeforeClass public static void setup() throws Exception { port = DefaultServer.getHostPort("default"); sslPort = port + 1; handlerPort = port + 2; DefaultServer.startSSLServer(); ssl = new UndertowXnioSsl(DefaultServer.getWorker().getXnio(), OptionMap.EMPTY, DefaultServer.getBufferPool(), DefaultServer.getClientSSLContext()); server = Undertow.builder() .addHttpsListener(handlerPort, DefaultServer.getHostAddress("default"), DefaultServer.getServerSslContext()) .setServerOption(UndertowOptions.ENABLE_SPDY, false) .setSocketOption(Options.REUSE_ADDRESSES, true) .setHandler(jvmRoute("JSESSIONID", "s1", path().addPrefixPath("/x-forwarded", new XForwardedHandler()))) .build(); server.start(); } @AfterClass public static void teardown() throws Exception { DefaultServer.stopSSLServer(); server.stop(); } private static void setProxyHandler(boolean rewriteHostHeader, boolean reuseXForwarded) throws Exception { DefaultServer.setRootHandler(new ProxyHandler(new LoadBalancingProxyClient() .setConnectionsPerThread(1) .addHost(new URI("https", null, DefaultServer.getHostAddress("default"), handlerPort, null, null, null), "s1", ssl, OptionMap.create(UndertowOptions.ENABLE_SPDY, false)) , 10000, ResponseCodeHandler.HANDLE_404, rewriteHostHeader, reuseXForwarded)); } @Test public void testXForwarded() throws Exception { setProxyHandler(false, false); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/x-forwarded"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals(port, Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue())); Assert.assertEquals("http", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue()); Assert.assertEquals("localhost", result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue()); Assert.assertEquals(DefaultServer.getDefaultServerAddress().getAddress().getHostAddress(), result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue()); } finally { client.getConnectionManager().shutdown(); } } @Test public void testXForwardedSsl() throws Exception { setProxyHandler(false, false); TestHttpClient client = new TestHttpClient(); try { client.setSSLContext(DefaultServer.getClientSSLContext()); HttpGet get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/x-forwarded"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals(sslPort, Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue())); Assert.assertEquals("https", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue()); Assert.assertEquals("localhost", result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue()); Assert.assertEquals(DefaultServer.getDefaultServerAddress().getAddress().getHostAddress(), result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue()); } finally { client.getConnectionManager().shutdown(); } } @Test public void testReuseXForwarded() throws Exception { setProxyHandler(false, true); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/x-forwarded"); get.addHeader(Headers.X_FORWARDED_FOR.toString(), "50.168.245.32"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals(port, Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue())); Assert.assertEquals("http", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue()); Assert.assertEquals("localhost", result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue()); Assert.assertEquals("50.168.245.32," + DefaultServer.getDefaultServerAddress().getAddress().getHostAddress(), result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue()); } finally { client.getConnectionManager().shutdown(); } } @Test public void testReqriteHostHeader() throws Exception { setProxyHandler(true, false); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/x-forwarded"); get.addHeader(Headers.X_FORWARDED_FOR.toString(), "50.168.245.32"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals(port, Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue())); Assert.assertEquals("http", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue()); Assert.assertEquals(String.format("localhost:%d", port), result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue()); Assert.assertEquals(DefaultServer.getDefaultServerAddress().getAddress().getHostAddress(), result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue()); } finally { client.getConnectionManager().shutdown(); } } protected static final class XForwardedHandler implements HttpHandler { @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { // Copy the X-Fowarded* headers into the response if (exchange.getRequestHeaders().contains(Headers.X_FORWARDED_FOR)) exchange.getResponseHeaders().put(Headers.X_FORWARDED_FOR, exchange.getRequestHeaders().getFirst(Headers.X_FORWARDED_FOR)); if (exchange.getRequestHeaders().contains(Headers.X_FORWARDED_PROTO)) exchange.getResponseHeaders().put(Headers.X_FORWARDED_PROTO, exchange.getRequestHeaders().getFirst(Headers.X_FORWARDED_PROTO)); if (exchange.getRequestHeaders().contains(Headers.X_FORWARDED_HOST)) exchange.getResponseHeaders().put(Headers.X_FORWARDED_HOST, exchange.getRequestHeaders().getFirst(Headers.X_FORWARDED_HOST)); if (exchange.getRequestHeaders().contains(Headers.X_FORWARDED_PORT)) exchange.getResponseHeaders().put(Headers.X_FORWARDED_PORT, exchange.getRequestHeaders().getFirst(Headers.X_FORWARDED_PORT)); } } }
core/src/test/java/io/undertow/server/handlers/proxy/ProxyHandlerXForwardedForTestCase.java
package io.undertow.server.handlers.proxy; import io.undertow.Undertow; import io.undertow.UndertowOptions; import io.undertow.protocols.ssl.UndertowXnioSsl; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.ResponseCodeHandler; import io.undertow.testutils.DefaultServer; import io.undertow.testutils.HttpOneOnly; import io.undertow.testutils.ProxyIgnore; import io.undertow.testutils.TestHttpClient; import io.undertow.util.Headers; import io.undertow.util.StatusCodes; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.xnio.OptionMap; import org.xnio.Options; import java.net.URI; import static io.undertow.Handlers.jvmRoute; import static io.undertow.Handlers.path; /** * Created by ivannagy on 8/26/14. */ @RunWith(DefaultServer.class) @HttpOneOnly @ProxyIgnore public class ProxyHandlerXForwardedForTestCase { protected static Undertow server; protected static int port; protected static int sslPort; protected static int handlerPort; protected static UndertowXnioSsl ssl; @BeforeClass public static void setup() throws Exception { port = DefaultServer.getHostPort("default"); sslPort = port + 1; handlerPort = port + 2; DefaultServer.startSSLServer(); ssl = new UndertowXnioSsl(DefaultServer.getWorker().getXnio(), OptionMap.EMPTY, DefaultServer.getBufferPool(), DefaultServer.getClientSSLContext()); server = Undertow.builder() .addHttpsListener(handlerPort, DefaultServer.getHostAddress("default"), DefaultServer.getServerSslContext()) .setServerOption(UndertowOptions.ENABLE_SPDY, false) .setSocketOption(Options.REUSE_ADDRESSES, true) .setHandler(jvmRoute("JSESSIONID", "s1", path().addPrefixPath("/x-forwarded", new XForwardedHandler()))) .build(); server.start(); } @AfterClass public static void teardown() throws Exception { DefaultServer.stopSSLServer(); server.stop(); } private static void setProxyHandler(boolean rewriteHostHeader, boolean reuseXForwarded) throws Exception { DefaultServer.setRootHandler(new ProxyHandler(new LoadBalancingProxyClient() .setConnectionsPerThread(1) .addHost(new URI("https", null, DefaultServer.getHostAddress("default"), handlerPort, null, null, null), "s1", ssl, OptionMap.create(UndertowOptions.ENABLE_SPDY, false)) , 10000, ResponseCodeHandler.HANDLE_404, rewriteHostHeader, reuseXForwarded)); } @Test public void testXForwarded() throws Exception { setProxyHandler(false, false); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/x-forwarded"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals(port, Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue())); Assert.assertEquals("http", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue()); Assert.assertEquals("localhost", result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue()); Assert.assertEquals("127.0.0.1", result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue()); } finally { client.getConnectionManager().shutdown(); } } @Test public void testXForwardedSsl() throws Exception { setProxyHandler(false, false); TestHttpClient client = new TestHttpClient(); try { client.setSSLContext(DefaultServer.getClientSSLContext()); HttpGet get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/x-forwarded"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals(sslPort, Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue())); Assert.assertEquals("https", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue()); Assert.assertEquals("localhost", result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue()); Assert.assertEquals("127.0.0.1", result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue()); } finally { client.getConnectionManager().shutdown(); } } @Test public void testReuseXForwarded() throws Exception { setProxyHandler(false, true); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/x-forwarded"); get.addHeader(Headers.X_FORWARDED_FOR.toString(), "50.168.245.32"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals(port, Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue())); Assert.assertEquals("http", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue()); Assert.assertEquals("localhost", result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue()); Assert.assertEquals("50.168.245.32,127.0.0.1", result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue()); } finally { client.getConnectionManager().shutdown(); } } @Test public void testReqriteHostHeader() throws Exception { setProxyHandler(true, false); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/x-forwarded"); get.addHeader(Headers.X_FORWARDED_FOR.toString(), "50.168.245.32"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals(port, Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue())); Assert.assertEquals("http", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue()); Assert.assertEquals(String.format("localhost:%d", port), result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue()); Assert.assertEquals("127.0.0.1", result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue()); } finally { client.getConnectionManager().shutdown(); } } protected static final class XForwardedHandler implements HttpHandler { @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { // Copy the X-Fowarded* headers into the response if (exchange.getRequestHeaders().contains(Headers.X_FORWARDED_FOR)) exchange.getResponseHeaders().put(Headers.X_FORWARDED_FOR, exchange.getRequestHeaders().getFirst(Headers.X_FORWARDED_FOR)); if (exchange.getRequestHeaders().contains(Headers.X_FORWARDED_PROTO)) exchange.getResponseHeaders().put(Headers.X_FORWARDED_PROTO, exchange.getRequestHeaders().getFirst(Headers.X_FORWARDED_PROTO)); if (exchange.getRequestHeaders().contains(Headers.X_FORWARDED_HOST)) exchange.getResponseHeaders().put(Headers.X_FORWARDED_HOST, exchange.getRequestHeaders().getFirst(Headers.X_FORWARDED_HOST)); if (exchange.getRequestHeaders().contains(Headers.X_FORWARDED_PORT)) exchange.getResponseHeaders().put(Headers.X_FORWARDED_PORT, exchange.getRequestHeaders().getFirst(Headers.X_FORWARDED_PORT)); } } }
Fix IPv6 test
core/src/test/java/io/undertow/server/handlers/proxy/ProxyHandlerXForwardedForTestCase.java
Fix IPv6 test
Java
apache-2.0
a35250054882010896e8880eb64e7c0f3b06081a
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.rt.debugger.agent; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * @author egor */ @SuppressWarnings("UseOfSystemOutOrSystemErr") public class CaptureStorage { public static final String GENERATED_INSERT_METHOD_POSTFIX = "$$$capture"; private static final ReferenceQueue KEY_REFERENCE_QUEUE = new ReferenceQueue(); private static final ConcurrentMap<WeakReference, CapturedStack> STORAGE = new ConcurrentHashMap<WeakReference, CapturedStack>(); @SuppressWarnings("SSBasedInspection") private static final ThreadLocal<Deque<CapturedStack>> CURRENT_STACKS = new ThreadLocal<Deque<CapturedStack>>() { @Override protected Deque<CapturedStack> initialValue() { return new LinkedList<CapturedStack>(); } }; @SuppressWarnings("StaticNonFinalField") public static boolean DEBUG; // set from debugger private static boolean ENABLED = true; //// METHODS CALLED FROM THE USER PROCESS @SuppressWarnings("unused") public static void capture(Object key) { if (!ENABLED) { return; } try { Throwable exception = new Throwable(); if (DEBUG) { System.out.println("capture " + getCallerDescriptor(exception) + " - " + key); } CapturedStack stack = createCapturedStack(exception, CURRENT_STACKS.get().peekLast()); processQueue(); WeakKey keyRef = new WeakKey(key, KEY_REFERENCE_QUEUE); STORAGE.put(keyRef, stack); } catch (Exception e) { handleException(e); } } @SuppressWarnings("unused") public static void insertEnter(Object key) { if (!ENABLED) { return; } try { //noinspection SuspiciousMethodCalls CapturedStack stack = STORAGE.get(new HardKey(key)); Deque<CapturedStack> currentStacks = CURRENT_STACKS.get(); currentStacks.add(stack); if (DEBUG) { System.out.println( "insert " + getCallerDescriptor(new Throwable()) + " -> " + key + ", stack saved (" + currentStacks.size() + ")"); } } catch (Exception e) { handleException(e); } } @SuppressWarnings("unused") public static void insertExit(Object key) { if (!ENABLED) { return; } try { Deque<CapturedStack> currentStacks = CURRENT_STACKS.get(); currentStacks.removeLast(); if (DEBUG) { System.out.println( "insert " + getCallerDescriptor(new Throwable()) + " <- " + key + ", stack removed (" + currentStacks.size() + ")"); } } catch (Exception e) { handleException(e); } } //// END - METHODS CALLED FROM THE USER PROCESS private static void processQueue() { WeakKey key; while ((key = (WeakKey)KEY_REFERENCE_QUEUE.poll()) != null) { STORAGE.remove(key); } } // only for map queries private static class HardKey { private final Object myKey; private final int myHash; HardKey(Object key) { myKey = key; myHash = System.identityHashCode(key); } @Override public boolean equals(Object o) { return this == o || (o instanceof WeakKey && ((WeakKey)o).get() == myKey); } public int hashCode() { return myHash; } } private static class WeakKey extends WeakReference { private final int myHash; WeakKey(Object key, ReferenceQueue q) { //noinspection unchecked super(key, q); myHash = System.identityHashCode(key); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof WeakKey)) return false; Object t = get(); Object u = ((WeakKey)o).get(); if (t == null || u == null) return false; return t == u; } @Override public int hashCode() { return myHash; } } private static CapturedStack createCapturedStack(Throwable exception, CapturedStack insertMatch) { if (insertMatch != null) { CapturedStack stack = new DeepCapturedStack(exception, insertMatch); if (stack.getRecursionDepth() > 100) { ArrayList<StackTraceElement> trace = getStackTrace(stack, 500); trace.trimToSize(); stack = new UnwindCapturedStack(trace); } return stack; } return new ExceptionCapturedStack(exception); } private interface CapturedStack { List<StackTraceElement> getStackTrace(); int getRecursionDepth(); } private static class UnwindCapturedStack implements CapturedStack { final List<StackTraceElement> myStackTraceElements; UnwindCapturedStack(List<StackTraceElement> elements) { myStackTraceElements = elements; } @Override public List<StackTraceElement> getStackTrace() { return myStackTraceElements; } @Override public int getRecursionDepth() { return 0; } } private static class ExceptionCapturedStack implements CapturedStack { final Throwable myException; private ExceptionCapturedStack(Throwable exception) { myException = exception; } @Override public List<StackTraceElement> getStackTrace() { StackTraceElement[] stackTrace = myException.getStackTrace(); return Arrays.asList(stackTrace).subList(1, stackTrace.length); } @Override public int getRecursionDepth() { return 0; } } private static class DeepCapturedStack extends ExceptionCapturedStack { final CapturedStack myInsertMatch; final int myRecursionDepth; DeepCapturedStack(Throwable exception, CapturedStack insertMatch) { super(exception); myInsertMatch = insertMatch; myRecursionDepth = insertMatch.getRecursionDepth() + 1; } @Override public int getRecursionDepth() { return myRecursionDepth; } } // to be run from the debugger @SuppressWarnings("unused") public static Object[][] getCurrentCapturedStack(int limit) { return wrapInArray(CURRENT_STACKS.get().peekLast(), limit); } // to be run from the debugger @SuppressWarnings("unused") public static Object[][] getRelatedStack(Object key, int limit) { //noinspection SuspiciousMethodCalls return wrapInArray(STORAGE.get(new HardKey(key)), limit); } private static Object[][] wrapInArray(CapturedStack stack, int limit) { if (stack == null) { return null; } List<StackTraceElement> stackTrace = getStackTrace(stack, limit); Object[][] res = new Object[stackTrace.size()][]; for (int i = 0; i < stackTrace.size(); i++) { StackTraceElement elem = stackTrace.get(i); if (elem == null) { res[i] = null; } else { res[i] = new Object[]{elem.getClassName(), elem.getFileName(), elem.getMethodName(), String.valueOf(elem.getLineNumber())}; } } return res; } private static ArrayList<StackTraceElement> getStackTrace(CapturedStack stack, int limit) { ArrayList<StackTraceElement> res = new ArrayList<StackTraceElement>(); while (stack != null && res.size() <= limit) { List<StackTraceElement> stackTrace = stack.getStackTrace(); if (stack instanceof DeepCapturedStack) { int depth = 0; for (; depth < stackTrace.size(); depth++) { if (stackTrace.get(depth).getMethodName().endsWith(GENERATED_INSERT_METHOD_POSTFIX)) { break; } } stackTrace = stackTrace.subList(0, depth + 2); stack = ((DeepCapturedStack)stack).myInsertMatch; } else { stack = null; } res.addAll(stackTrace); if (stack != null) { res.add(null); } } return res; } public static void setEnabled(boolean enabled) { ENABLED = enabled; } private static void handleException(Throwable e) { ENABLED = false; System.err.println("Critical error in IDEA Async Stacktraces instrumenting agent. Agent is now disabled. Please report to IDEA support:"); //noinspection CallToPrintStackTrace e.printStackTrace(); } private static String getCallerDescriptor(Throwable e) { StackTraceElement caller = e.getStackTrace()[1]; return caller.getClassName() + "." + caller.getMethodName(); } }
java/debugger/debugger-agent-storage/src/com/intellij/rt/debugger/agent/CaptureStorage.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.rt.debugger.agent; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * @author egor */ @SuppressWarnings("UseOfSystemOutOrSystemErr") public class CaptureStorage { public static final String GENERATED_INSERT_METHOD_POSTFIX = "$$$capture"; private static final ReferenceQueue KEY_REFERENCE_QUEUE = new ReferenceQueue(); private static final ConcurrentMap<WeakReference, CapturedStack> STORAGE = new ConcurrentHashMap<WeakReference, CapturedStack>(); @SuppressWarnings("SSBasedInspection") private static final ThreadLocal<Deque<CapturedStack>> CURRENT_STACKS = new ThreadLocal<Deque<CapturedStack>>() { @Override protected Deque<CapturedStack> initialValue() { return new LinkedList<CapturedStack>(); } }; @SuppressWarnings("StaticNonFinalField") public static boolean DEBUG; // set from debugger private static boolean ENABLED = true; //// METHODS CALLED FROM THE USER PROCESS @SuppressWarnings("unused") public static void capture(Object key) { if (!ENABLED) { return; } try { Throwable exception = new Throwable(); if (DEBUG) { System.out.println("capture " + getCallerDescriptor(exception) + " - " + key); } CapturedStack stack = createCapturedStack(exception, CURRENT_STACKS.get().peekLast()); processQueue(); WeakKey keyRef = new WeakKey(key, stack, KEY_REFERENCE_QUEUE); STORAGE.put(keyRef, stack); } catch (Exception e) { handleException(e); } } @SuppressWarnings("unused") public static void insertEnter(Object key) { if (!ENABLED) { return; } try { //noinspection SuspiciousMethodCalls CapturedStack stack = STORAGE.get(new HardKey(key)); Deque<CapturedStack> currentStacks = CURRENT_STACKS.get(); currentStacks.add(stack); if (DEBUG) { System.out.println( "insert " + getCallerDescriptor(new Throwable()) + " -> " + key + ", stack saved (" + currentStacks.size() + ")"); } } catch (Exception e) { handleException(e); } } @SuppressWarnings("unused") public static void insertExit(Object key) { if (!ENABLED) { return; } try { Deque<CapturedStack> currentStacks = CURRENT_STACKS.get(); currentStacks.removeLast(); if (DEBUG) { System.out.println( "insert " + getCallerDescriptor(new Throwable()) + " <- " + key + ", stack removed (" + currentStacks.size() + ")"); } } catch (Exception e) { handleException(e); } } //// END - METHODS CALLED FROM THE USER PROCESS private static void processQueue() { WeakKey key; while ((key = (WeakKey)KEY_REFERENCE_QUEUE.poll()) != null) { STORAGE.remove(key, key.myValue); } } // only for map queries private static class HardKey { private final Object myKey; private final int myHash; HardKey(Object key) { myKey = key; myHash = System.identityHashCode(key); } @Override public boolean equals(Object o) { return this == o || (o instanceof WeakKey && ((WeakKey)o).get() == myKey); } public int hashCode() { return myHash; } } private static class WeakKey extends WeakReference { private final int myHash; private final CapturedStack myValue; WeakKey(Object key, CapturedStack value, ReferenceQueue q) { //noinspection unchecked super(key, q); myHash = System.identityHashCode(key); myValue = value; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof WeakKey)) return false; Object t = get(); Object u = ((WeakKey)o).get(); if (t == null || u == null) return false; return t == u; } @Override public int hashCode() { return myHash; } } private static CapturedStack createCapturedStack(Throwable exception, CapturedStack insertMatch) { if (insertMatch != null) { CapturedStack stack = new DeepCapturedStack(exception, insertMatch); if (stack.getRecursionDepth() > 100) { ArrayList<StackTraceElement> trace = getStackTrace(stack, 500); trace.trimToSize(); stack = new UnwindCapturedStack(trace); } return stack; } return new ExceptionCapturedStack(exception); } private interface CapturedStack { List<StackTraceElement> getStackTrace(); int getRecursionDepth(); } private static class UnwindCapturedStack implements CapturedStack { final List<StackTraceElement> myStackTraceElements; UnwindCapturedStack(List<StackTraceElement> elements) { myStackTraceElements = elements; } @Override public List<StackTraceElement> getStackTrace() { return myStackTraceElements; } @Override public int getRecursionDepth() { return 0; } } private static class ExceptionCapturedStack implements CapturedStack { final Throwable myException; private ExceptionCapturedStack(Throwable exception) { myException = exception; } @Override public List<StackTraceElement> getStackTrace() { StackTraceElement[] stackTrace = myException.getStackTrace(); return Arrays.asList(stackTrace).subList(1, stackTrace.length); } @Override public int getRecursionDepth() { return 0; } } private static class DeepCapturedStack extends ExceptionCapturedStack { final CapturedStack myInsertMatch; final int myRecursionDepth; DeepCapturedStack(Throwable exception, CapturedStack insertMatch) { super(exception); myInsertMatch = insertMatch; myRecursionDepth = insertMatch.getRecursionDepth() + 1; } @Override public int getRecursionDepth() { return myRecursionDepth; } } // to be run from the debugger @SuppressWarnings("unused") public static Object[][] getCurrentCapturedStack(int limit) { return wrapInArray(CURRENT_STACKS.get().peekLast(), limit); } // to be run from the debugger @SuppressWarnings("unused") public static Object[][] getRelatedStack(Object key, int limit) { //noinspection SuspiciousMethodCalls return wrapInArray(STORAGE.get(new HardKey(key)), limit); } private static Object[][] wrapInArray(CapturedStack stack, int limit) { if (stack == null) { return null; } List<StackTraceElement> stackTrace = getStackTrace(stack, limit); Object[][] res = new Object[stackTrace.size()][]; for (int i = 0; i < stackTrace.size(); i++) { StackTraceElement elem = stackTrace.get(i); if (elem == null) { res[i] = null; } else { res[i] = new Object[]{elem.getClassName(), elem.getFileName(), elem.getMethodName(), String.valueOf(elem.getLineNumber())}; } } return res; } private static ArrayList<StackTraceElement> getStackTrace(CapturedStack stack, int limit) { ArrayList<StackTraceElement> res = new ArrayList<StackTraceElement>(); while (stack != null && res.size() <= limit) { List<StackTraceElement> stackTrace = stack.getStackTrace(); if (stack instanceof DeepCapturedStack) { int depth = 0; for (; depth < stackTrace.size(); depth++) { if (stackTrace.get(depth).getMethodName().endsWith(GENERATED_INSERT_METHOD_POSTFIX)) { break; } } stackTrace = stackTrace.subList(0, depth + 2); stack = ((DeepCapturedStack)stack).myInsertMatch; } else { stack = null; } res.addAll(stackTrace); if (stack != null) { res.add(null); } } return res; } public static void setEnabled(boolean enabled) { ENABLED = enabled; } private static void handleException(Throwable e) { ENABLED = false; System.err.println("Critical error in IDEA Async Stacktraces instrumenting agent. Agent is now disabled. Please report to IDEA support:"); //noinspection CallToPrintStackTrace e.printStackTrace(); } private static String getCallerDescriptor(Throwable e) { StackTraceElement caller = e.getStackTrace()[1]; return caller.getClassName() + "." + caller.getMethodName(); } }
IDEA-198992 OOM in CaptureStorage
java/debugger/debugger-agent-storage/src/com/intellij/rt/debugger/agent/CaptureStorage.java
IDEA-198992 OOM in CaptureStorage
Java
apache-2.0
d58d49dd23afc14b1b89b0f0389cfa623f1c7ce6
0
apache/pdfbox,kalaspuffar/pdfbox,apache/pdfbox,kalaspuffar/pdfbox
/* * 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.pdfbox.pdmodel.graphics.color; import java.awt.Color; import java.awt.Paint; import java.awt.color.ColorSpace; import java.awt.color.ICC_ColorSpace; import java.io.IOException; import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.pdmodel.graphics.pattern.PDPatternResources; /** * This class represents a color space and the color value for that colorspace. * * @author <a href="mailto:ben@benlitchfield.com">Ben Litchfield</a> * */ public class PDColorState implements Cloneable { /** * Log instance. */ private static final Log LOG = LogFactory.getLog(PDColorState.class); /** * The default color that can be set to replace all colors in {@link ICC_ColorSpace ICC color spaces}. * * @see #setIccOverrideColor(Color) */ private static volatile Color iccOverrideColor = Color.getColor("org.apache.pdfbox.ICC_override_color"); /** * Sets the default color to replace all colors in {@link ICC_ColorSpace ICC color spaces}. This will work around a * potential JVM crash caused by broken native ICC color manipulation code in the Sun class libraries. * <p> * The default override can be specified by setting the color code in * <code>org.apache.pdfbox.ICC_override_color</code> system property (see {@link Color#getColor(String)}. If this * system property is not specified, then the override is not enabled unless this method is explicitly called. * * @param color ICC override color, or <code>null</code> to disable the override * @see <a href="https://issues.apache.org/jira/browse/PDFBOX-511">PDFBOX-511</a> * @since Apache PDFBox 0.8.1 */ public static void setIccOverrideColor(Color color) { iccOverrideColor = color; } private PDColorSpace colorSpace = new PDDeviceGray(); private COSArray colorSpaceValue = new COSArray(); private PDPatternResources pattern = null; /** * Cached Java AWT color based on the current color space and value. The value is cleared whenever the color space * or value is set. * * @see #getJavaColor() */ private Color color = null; private Paint paint = null; /** * Default constructor. * */ public PDColorState() { setColorSpaceValue(new float[] { 0 }); } /** * {@inheritDoc} */ public Object clone() { PDColorState retval = new PDColorState(); retval.colorSpace = colorSpace; retval.colorSpaceValue.clear(); retval.colorSpaceValue.addAll(colorSpaceValue); retval.setPattern(getPattern()); return retval; } /** * Returns the Java AWT color based on the current color space and value. * * @return current Java AWT color * @throws IOException if the current color can not be created */ public Color getJavaColor() throws IOException { if (color == null && colorSpaceValue.size() > 0) { color = createColor(); } return color; } /** * Returns the Java AWT paint based on the current pattern. * * @param pageHeight the height of the current page * @return current Java AWT paint * * @throws IOException if the current color can not be created */ public Paint getPaint(int pageHeight) throws IOException { if (paint == null && pattern != null) { paint = pattern.getPaint(pageHeight); } return paint; } /** * Create the current color from the colorspace and values. * * @return The current awt color. * @throws IOException If there is an error creating the color. */ private Color createColor() throws IOException { float[] components = colorSpaceValue.toFloatArray(); try { String csName = colorSpace.getName(); if (PDDeviceRGB.NAME.equals(csName) && components.length == 3) { // for some reason, when using RGB and the RGB colorspace // the new Color doesn't maintain exactly the same values // I think some color conversion needs to take place first // for now we will just make rgb a special case. return new Color(components[0], components[1], components[2]); } else if (PDLab.NAME.equals(csName)) { // transform the color values from Lab- to RGB-space float[] csComponents = colorSpace.getJavaColorSpace().toRGB(components); return new Color(csComponents[0], csComponents[1], csComponents[2]); } else { if (components.length == 1) { if (PDSeparation.NAME.equals(csName)) { // Use that component as a single-integer RGB value return new Color((int) components[0]); } if (PDDeviceGray.NAME.equals(csName)) { // Handling DeviceGray as a special case as with JVM 1.5.0_15 // and maybe others printing on Windows fails with an // ArrayIndexOutOfBoundsException when selecting colors // and strokes e.g. sun.awt.windows.WPrinterJob.setTextColor return new Color(components[0], components[0], components[0]); } } Color override = iccOverrideColor; ColorSpace cs = colorSpace.getJavaColorSpace(); if (cs instanceof ICC_ColorSpace && override != null) { LOG.warn("Using an ICC override color to avoid a potential" + " JVM crash (see PDFBOX-511)"); return override; } else { return new Color(cs, components, 1f); } } } // Catch IOExceptions from PDColorSpace.getJavaColorSpace(), but // possibly also IllegalArgumentExceptions or other RuntimeExceptions // from the potentially complex color management code. catch (Exception e) { Color cGuess; String sMsg = "Unable to create the color instance " + Arrays.toString(components) + " in color space " + colorSpace + "; guessing color ... "; try { switch (components.length) { case 1:// Use that component as a single-integer RGB value cGuess = new Color((int) components[0]); sMsg += "\nInterpretating as single-integer RGB"; break; case 3: // RGB cGuess = new Color(components[0], components[1], components[2]); sMsg += "\nInterpretating as RGB"; break; case 4: // CMYK try { // try to use the default CMYK color profile float[] rgb = PDDeviceCMYK.INSTANCE.getJavaColorSpace().toRGB(components); cGuess = new Color(rgb[0], rgb[1], rgb[2]); sMsg += "\nInterpretating as CMYK using default ICC profile"; } catch (Exception e1) { // fallback to naive conversion to RGB float r, g, b, k; k = components[3]; r = components[0] * (1f - k) + k; g = components[1] * (1f - k) + k; b = components[2] * (1f - k) + k; r = (1f - r); g = (1f - g); b = (1f - b); cGuess = new Color(r, g, b); sMsg += "\nInterpretating as CMYK without ICC profile"; } break; default: sMsg += "\nUnable to guess using " + components.length + " components; using black instead"; cGuess = Color.BLACK; } } catch (Exception e2) { sMsg += "\nColor interpolation failed; using black instead\n"; sMsg += e2.toString(); cGuess = Color.BLACK; } LOG.warn(sMsg, e); return cGuess; } } /** * Constructor with an existing color set. Default colorspace is PDDeviceGray. * * @param csValues The color space values. */ public PDColorState(COSArray csValues) { colorSpaceValue = csValues; } /** * This will get the current colorspace. * * @return The current colorspace. */ public PDColorSpace getColorSpace() { return colorSpace; } /** * This will set the current colorspace. * * @param value The new colorspace. */ public void setColorSpace(PDColorSpace value) { colorSpace = value; // Clear color/paint cache and current pattern color = null; paint = null; pattern = null; } /** * This will get the color space values. Either 1 for gray or 3 for RGB. * * @return The colorspace values. */ public float[] getColorSpaceValue() { return colorSpaceValue.toFloatArray(); } /** * This will get the color space values. Either 1 for gray or 3 for RGB. * * @return The colorspace values. */ public COSArray getCOSColorSpaceValue() { return colorSpaceValue; } /** * This will update the colorspace values. * * @param value The new colorspace values. */ public void setColorSpaceValue(float[] value) { colorSpaceValue.setFloatArray(value); // Clear color/paint and current pattern color = null; paint = null; pattern = null; } /** * This will get the current pattern. * * @return The current pattern. */ public PDPatternResources getPattern() { return pattern; } /** * This will update the current pattern. * * @param patternValue The new pattern. */ public void setPattern(PDPatternResources patternValue) { pattern = patternValue; // Clear color/paint cache color = null; paint = null; } }
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/color/PDColorState.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.pdmodel.graphics.color; import java.awt.Color; import java.awt.Paint; import java.awt.color.ColorSpace; import java.awt.color.ICC_ColorSpace; import java.io.IOException; import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.pdmodel.graphics.pattern.PDPatternResources; /** * This class represents a color space and the color value for that colorspace. * * @author <a href="mailto:ben@benlitchfield.com">Ben Litchfield</a> * */ public class PDColorState implements Cloneable { /** * Log instance. */ private static final Log LOG = LogFactory.getLog(PDColorState.class); /** * The default color that can be set to replace all colors in {@link ICC_ColorSpace ICC color spaces}. * * @see #setIccOverrideColor(Color) */ private static volatile Color iccOverrideColor = Color.getColor("org.apache.pdfbox.ICC_override_color"); /** * Sets the default color to replace all colors in {@link ICC_ColorSpace ICC color spaces}. This will work around a * potential JVM crash caused by broken native ICC color manipulation code in the Sun class libraries. * <p> * The default override can be specified by setting the color code in * <code>org.apache.pdfbox.ICC_override_color</code> system property (see {@link Color#getColor(String)}. If this * system property is not specified, then the override is not enabled unless this method is explicitly called. * * @param color ICC override color, or <code>null</code> to disable the override * @see <a href="https://issues.apache.org/jira/browse/PDFBOX-511">PDFBOX-511</a> * @since Apache PDFBox 0.8.1 */ public static void setIccOverrideColor(Color color) { iccOverrideColor = color; } private PDColorSpace colorSpace = new PDDeviceGray(); private COSArray colorSpaceValue = new COSArray(); private PDPatternResources pattern = null; /** * Cached Java AWT color based on the current color space and value. The value is cleared whenever the color space * or value is set. * * @see #getJavaColor() */ private Color color = null; private Paint paint = null; /** * Default constructor. * */ public PDColorState() { setColorSpaceValue(new float[] { 0 }); } /** * {@inheritDoc} */ public Object clone() { PDColorState retval = new PDColorState(); retval.colorSpace = colorSpace; retval.colorSpaceValue.clear(); retval.colorSpaceValue.addAll(colorSpaceValue); retval.setPattern(getPattern()); return retval; } /** * Returns the Java AWT color based on the current color space and value. * * @return current Java AWT color * @throws IOException if the current color can not be created */ public Color getJavaColor() throws IOException { if (color == null && colorSpaceValue.size() > 0) { color = createColor(); } return color; } /** * Returns the Java AWT paint based on the current pattern. * * @param pageHeight the height of the current page * @return current Java AWT paint * * @throws IOException if the current color can not be created */ public Paint getPaint(int pageHeight) throws IOException { if (paint == null && pattern != null) { paint = pattern.getPaint(pageHeight); } return paint; } /** * Create the current color from the colorspace and values. * * @return The current awt color. * @throws IOException If there is an error creating the color. */ private Color createColor() throws IOException { float[] components = colorSpaceValue.toFloatArray(); try { String csName = colorSpace.getName(); if (PDDeviceRGB.NAME.equals(csName) && components.length == 3) { // for some reason, when using RGB and the RGB colorspace // the new Color doesn't maintain exactly the same values // I think some color conversion needs to take place first // for now we will just make rgb a special case. return new Color(components[0], components[1], components[2]); } else if (PDLab.NAME.equals(csName)) { // transform the color values from Lab- to RGB-space float[] csComponents = colorSpace.getJavaColorSpace().toRGB(components); return new Color(csComponents[0], csComponents[1], csComponents[2]); } else { if (components.length == 1) { if (PDSeparation.NAME.equals(csName)) { // Use that component as a single-integer RGB value return new Color((int) components[0]); } if (PDDeviceGray.NAME.equals(csName)) { // Handling DeviceGray as a special case as with JVM 1.5.0_15 // and maybe others printing on Windows fails with an // ArrayIndexOutOfBoundsException when selecting colors // and strokes e.g. sun.awt.windows.WPrinterJob.setTextColor return new Color(components[0], components[0], components[0]); } } Color override = iccOverrideColor; ColorSpace cs = colorSpace.getJavaColorSpace(); if (cs instanceof ICC_ColorSpace && override != null) { LOG.warn("Using an ICC override color to avoid a potential" + " JVM crash (see PDFBOX-511)"); return override; } else { return new Color(cs, components, 1f); } } } // Catch IOExceptions from PDColorSpace.getJavaColorSpace(), but // possibly also IllegalArgumentExceptions or other RuntimeExceptions // from the potentially complex color management code. catch (Exception e) { Color cGuess; String sMsg = "Unable to create the color instance " + Arrays.toString(components) + " in color space " + colorSpace + "; guessing color ... "; try { switch (components.length) { case 1:// Use that component as a single-integer RGB value cGuess = new Color((int) components[0]); sMsg += "\nInterpretating as single-integer RGB"; break; case 3: // RGB cGuess = new Color(components[0], components[1], components[2]); sMsg += "\nInterpretating as RGB"; break; case 4: // CMYK try { // try to use the default CMYK color profile float[] rgb = PDDeviceCMYK.INSTANCE.getJavaColorSpace().toRGB(components); cGuess = new Color(rgb[0], rgb[1], rgb[2]); sMsg += "\nInterpretating as CMYK using default ICC profile"; } catch (Exception e1) { // fallback to naive conversion to RGB float r, g, b, k; k = components[3]; r = components[0] * (1f - k) + k; g = components[1] * (1f - k) + k; b = components[2] * (1f - k) + k; r = (1f - r); g = (1f - g); b = (1f - b); cGuess = new Color(r, g, b); sMsg += "\nInterpretating as CMYK without ICC profile"; } break; default: sMsg += "\nUnable to guess using " + components.length + " components; using black instead"; cGuess = Color.BLACK; } } catch (Exception e2) { sMsg += "\nColor interpolation failed; using black instead\n"; sMsg += e2.toString(); cGuess = Color.BLACK; } LOG.warn(sMsg, e); return cGuess; } } /** * Constructor with an existing color set. Default colorspace is PDDeviceGray. * * @param csValues The color space values. */ public PDColorState(COSArray csValues) { colorSpaceValue = csValues; } /** * This will get the current colorspace. * * @return The current colorspace. */ public PDColorSpace getColorSpace() { return colorSpace; } /** * This will set the current colorspace. * * @param value The new colorspace. */ public void setColorSpace(PDColorSpace value) { colorSpace = value; // Clear color cache and current pattern color = null; pattern = null; } /** * This will get the color space values. Either 1 for gray or 3 for RGB. * * @return The colorspace values. */ public float[] getColorSpaceValue() { return colorSpaceValue.toFloatArray(); } /** * This will get the color space values. Either 1 for gray or 3 for RGB. * * @return The colorspace values. */ public COSArray getCOSColorSpaceValue() { return colorSpaceValue; } /** * This will update the colorspace values. * * @param value The new colorspace values. */ public void setColorSpaceValue(float[] value) { colorSpaceValue.setFloatArray(value); // Clear color cache and current pattern color = null; pattern = null; } /** * This will get the current pattern. * * @return The current pattern. */ public PDPatternResources getPattern() { return pattern; } /** * This will update the current pattern. * * @param patternValue The new pattern. */ public void setPattern(PDPatternResources patternValue) { pattern = patternValue; // Clear color cache color = null; } }
PDFBOX-1442: clear cached paint value git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1563662 13f79535-47bb-0310-9956-ffa450edef68
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/color/PDColorState.java
PDFBOX-1442: clear cached paint value
Java
apache-2.0
2feb36fc51e085040d7978f919f0dcf9a14a2b5f
0
cushon/bazel,dslomov/bazel-windows,dslomov/bazel,akira-baruah/bazel,davidzchen/bazel,bazelbuild/bazel,cushon/bazel,ButterflyNetwork/bazel,werkt/bazel,meteorcloudy/bazel,dslomov/bazel,katre/bazel,ButterflyNetwork/bazel,safarmer/bazel,dslomov/bazel-windows,dslomov/bazel,ButterflyNetwork/bazel,davidzchen/bazel,davidzchen/bazel,ulfjack/bazel,akira-baruah/bazel,twitter-forks/bazel,ulfjack/bazel,werkt/bazel,ButterflyNetwork/bazel,perezd/bazel,akira-baruah/bazel,meteorcloudy/bazel,ButterflyNetwork/bazel,twitter-forks/bazel,perezd/bazel,dslomov/bazel,dslomov/bazel-windows,cushon/bazel,katre/bazel,twitter-forks/bazel,akira-baruah/bazel,werkt/bazel,katre/bazel,davidzchen/bazel,dslomov/bazel,werkt/bazel,twitter-forks/bazel,safarmer/bazel,twitter-forks/bazel,perezd/bazel,ulfjack/bazel,katre/bazel,bazelbuild/bazel,akira-baruah/bazel,meteorcloudy/bazel,perezd/bazel,ButterflyNetwork/bazel,twitter-forks/bazel,bazelbuild/bazel,akira-baruah/bazel,katre/bazel,katre/bazel,safarmer/bazel,davidzchen/bazel,bazelbuild/bazel,dslomov/bazel,perezd/bazel,cushon/bazel,werkt/bazel,meteorcloudy/bazel,twitter-forks/bazel,ulfjack/bazel,safarmer/bazel,cushon/bazel,meteorcloudy/bazel,cushon/bazel,dslomov/bazel-windows,bazelbuild/bazel,meteorcloudy/bazel,ulfjack/bazel,dslomov/bazel,safarmer/bazel,davidzchen/bazel,dslomov/bazel-windows,dslomov/bazel-windows,perezd/bazel,meteorcloudy/bazel,werkt/bazel,davidzchen/bazel,safarmer/bazel,ulfjack/bazel,bazelbuild/bazel,ulfjack/bazel,perezd/bazel
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.android.desugar.runtime; import android.accessibilityservice.AccessibilityService; import android.accessibilityservice.AccessibilityService.ScreenshotResult; import android.app.DirectAction; import android.os.Bundle; import android.os.CancellationSignal; import android.service.voice.VoiceInteractionSession; import android.telephony.AvailableNetworkInfo; import android.telephony.TelephonyManager; import java.util.List; import java.util.concurrent.Executor; import java.util.function.Consumer; /** * Conversion from desugared to built-in {@link Consumer} for calling built-in Android APIs (see * b/128638076). */ // TODO(b/74087778): Unnecessary when j$.u.f.Consumer becomes subtype of built-in j.u.f.Consumer @SuppressWarnings("AndroidJdkLibsChecker") public final class ConsumerWrapper<T> implements Consumer<T> { private final j$.util.function.Consumer<T> wrapped; private ConsumerWrapper(j$.util.function.Consumer<T> wrapped) { this.wrapped = wrapped; } @Override public void accept(T t) { wrapped.accept(t); } public static void setPreferredOpportunisticDataSubscription( TelephonyManager receiver, int subId, boolean needValidation, Executor executor, j$.util.function.Consumer<Integer> callback) { receiver.setPreferredOpportunisticDataSubscription( subId, needValidation, executor, callback != null ? new ConsumerWrapper<Integer>(callback) : null); } public static void updateAvailableNetworks( TelephonyManager receiver, List<AvailableNetworkInfo> availableNetworks, Executor executor, j$.util.function.Consumer<Integer> callback) { receiver.updateAvailableNetworks( availableNetworks, executor, callback != null ? new ConsumerWrapper<Integer>(callback) : null); } public static void performDirectAction( VoiceInteractionSession receiver, DirectAction action, Bundle extras, CancellationSignal cancellationSignal, Executor resultExecutor, j$.util.function.Consumer<Bundle> resultListener) { receiver.performDirectAction( action, extras, cancellationSignal, resultExecutor, resultListener != null ? new ConsumerWrapper<Bundle>(resultListener) : null); } public static void requestDirectActions( VoiceInteractionSession receiver, VoiceInteractionSession.ActivityId activityId, CancellationSignal cancellationSignal, Executor resultExecutor, j$.util.function.Consumer<List<DirectAction>> callback) { receiver.requestDirectActions( activityId, cancellationSignal, resultExecutor, callback != null ? new ConsumerWrapper<List<DirectAction>>(callback) : null); } public static boolean takeScreenshot( AccessibilityService receiver, int displayId, Executor resultExecutor, j$.util.function.Consumer<ScreenshotResult> callback) { return receiver.takeScreenshot( displayId, resultExecutor, callback != null ? new ConsumerWrapper<ScreenshotResult>(callback) : null); } }
src/tools/android/java/com/google/devtools/build/android/desugar/runtime/ConsumerWrapper.java
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.android.desugar.runtime; import android.app.DirectAction; import android.os.Bundle; import android.os.CancellationSignal; import android.service.voice.VoiceInteractionSession; import android.telephony.AvailableNetworkInfo; import android.telephony.TelephonyManager; import java.util.List; import java.util.concurrent.Executor; import java.util.function.Consumer; /** * Conversion from desugared to built-in {@link Consumer} for calling built-in Android APIs (see * b/128638076). */ // TODO(b/74087778): Unnecessary when j$.u.f.Consumer becomes subtype of built-in j.u.f.Consumer @SuppressWarnings("AndroidJdkLibsChecker") public final class ConsumerWrapper<T> implements Consumer<T> { private final j$.util.function.Consumer<T> wrapped; private ConsumerWrapper(j$.util.function.Consumer<T> wrapped) { this.wrapped = wrapped; } @Override public void accept(T t) { wrapped.accept(t); } public static void setPreferredOpportunisticDataSubscription( TelephonyManager receiver, int subId, boolean needValidation, Executor executor, j$.util.function.Consumer<Integer> callback) { receiver.setPreferredOpportunisticDataSubscription( subId, needValidation, executor, callback != null ? new ConsumerWrapper<Integer>(callback) : null); } public static void updateAvailableNetworks( TelephonyManager receiver, List<AvailableNetworkInfo> availableNetworks, Executor executor, j$.util.function.Consumer<Integer> callback) { receiver.updateAvailableNetworks( availableNetworks, executor, callback != null ? new ConsumerWrapper<Integer>(callback) : null); } public static void performDirectAction( VoiceInteractionSession receiver, DirectAction action, Bundle extras, CancellationSignal cancellationSignal, Executor resultExecutor, j$.util.function.Consumer<Bundle> resultListener) { receiver.performDirectAction( action, extras, cancellationSignal, resultExecutor, resultListener != null ? new ConsumerWrapper<Bundle>(resultListener) : null); } public static void requestDirectActions( VoiceInteractionSession receiver, VoiceInteractionSession.ActivityId activityId, CancellationSignal cancellationSignal, Executor resultExecutor, j$.util.function.Consumer<List<DirectAction>> callback) { receiver.requestDirectActions( activityId, cancellationSignal, resultExecutor, callback != null ? new ConsumerWrapper<List<DirectAction>>(callback) : null); } }
Add takeScreenshot() to the stable version of ConsumerWrapper.java PiperOrigin-RevId: 302104263
src/tools/android/java/com/google/devtools/build/android/desugar/runtime/ConsumerWrapper.java
Add takeScreenshot() to the stable version of ConsumerWrapper.java
Java
apache-2.0
efb0cf2800b44722b572ff6cd08f19e9500cc2e9
0
smartpcr/stream-lib,orneryhippo/stream-lib,orneryhippo/stream-lib,smartpcr/stream-lib,cykl/stream-lib,joychugh/stream-lib,tempbottle/stream-lib,tempbottle/stream-lib,joychugh/stream-lib,oertl/stream-lib,cykl/stream-lib,oertl/stream-lib
/* * Copyright (C) 2011 Clearspring Technologies, 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.clearspring.analytics.stream.cardinality; import org.junit.Test; import java.io.IOException; import java.util.Arrays; import static org.junit.Assert.*; public class TestHyperLogLog { @Test public void testComputeCount() { HyperLogLog hyperLogLog = new HyperLogLog(.05); hyperLogLog.offer(0); hyperLogLog.offer(1); hyperLogLog.offer(2); hyperLogLog.offer(3); hyperLogLog.offer(16); hyperLogLog.offer(17); hyperLogLog.offer(18); hyperLogLog.offer(19); hyperLogLog.offer(19); assertEquals(8, hyperLogLog.cardinality()); } @Test public void testSerialization() throws IOException { HyperLogLog hll = new HyperLogLog(.05); hll.offer("a"); hll.offer("b"); hll.offer("c"); hll.offer("d"); hll.offer("e"); HyperLogLog hll2 = HyperLogLog.Builder.build(hll.getBytes()); assertArrayEquals(hll.getBits(), hll2.getBits()); assertEquals(hll.cardinality(), hll2.cardinality()); assertEquals(hll.getRegisterSize(), hll2.getRegisterSize()); } @Test public void testICardinality() { LogLog hyperLogLog = new LogLog.Builder(16).build(); int size = 50000000; for (int i = 0; i < size; i++) { hyperLogLog.offer(TestICardinality.streamElement(i)); } long estimate = hyperLogLog.cardinality(); double err = Math.abs(estimate - size) / (double) size; assertTrue(err < .1); } @Test public void testMerge() throws CardinalityMergeException { int numToMerge = 5; double rds = 0.005; int cardinality = 1000; HyperLogLog[] hyperLogLogs = new HyperLogLog[numToMerge]; for(int i=0; i<numToMerge; i++) { hyperLogLogs[i] = new HyperLogLog(rds); for(int j=0; j<cardinality; j++) hyperLogLogs[i].offer(Math.random()); } int expectedCardinality = numToMerge*cardinality; HyperLogLog hll = hyperLogLogs[0]; hyperLogLogs = Arrays.asList(hyperLogLogs).subList(1, hyperLogLogs.length).toArray(new HyperLogLog[0]); long mergedEstimate = hll.merge(hyperLogLogs).cardinality(); double error = Math.abs(mergedEstimate - expectedCardinality) / (double)expectedCardinality; assertTrue(error < .01); } }
src/test/java/com/clearspring/analytics/stream/cardinality/TestHyperLogLog.java
/* * Copyright (C) 2011 Clearspring Technologies, 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.clearspring.analytics.stream.cardinality; import org.junit.Test; import java.io.IOException; import java.util.Arrays; import static org.junit.Assert.*; public class TestHyperLogLog { @Test public void testComputeCount() { HyperLogLog hyperLogLog = new HyperLogLog(.05); hyperLogLog.offer(0); hyperLogLog.offer(1); hyperLogLog.offer(2); hyperLogLog.offer(3); hyperLogLog.offer(16); hyperLogLog.offer(17); hyperLogLog.offer(18); hyperLogLog.offer(19); hyperLogLog.offer(19); assertEquals(8, hyperLogLog.cardinality()); } @Test public void testSerialization() throws IOException { HyperLogLog hll = new HyperLogLog(.05); hll.offer("a"); hll.offer("b"); hll.offer("c"); hll.offer("d"); hll.offer("e"); HyperLogLog hll2 = new HyperLogLog(HyperLogLog.getBits(hll.getBytes()), .05, 100000); assertArrayEquals(hll.getBits(), hll2.getBits()); assertEquals(hll.cardinality(), hll2.cardinality()); assertEquals(hll.getRegisterSize(), hll2.getRegisterSize()); } @Test public void testICardinality() { LogLog hyperLogLog = new LogLog.Builder(16).build(); int size = 50000000; for (int i = 0; i < size; i++) { hyperLogLog.offer(TestICardinality.streamElement(i)); } long estimate = hyperLogLog.cardinality(); double err = Math.abs(estimate - size) / (double) size; assertTrue(err < .1); } @Test public void testMerge() throws CardinalityMergeException { int numToMerge = 5; double rds = 0.005; int cardinality = 1000; HyperLogLog[] hyperLogLogs = new HyperLogLog[numToMerge]; for(int i=0; i<numToMerge; i++) { hyperLogLogs[i] = new HyperLogLog(rds); for(int j=0; j<cardinality; j++) hyperLogLogs[i].offer(Math.random()); } int expectedCardinality = numToMerge*cardinality; HyperLogLog hll = hyperLogLogs[0]; hyperLogLogs = Arrays.asList(hyperLogLogs).subList(1, hyperLogLogs.length).toArray(new HyperLogLog[0]); long mergedEstimate = hll.merge(hyperLogLogs).cardinality(); double error = Math.abs(mergedEstimate - expectedCardinality) / (double)expectedCardinality; assertTrue(error < .01); } }
fix test
src/test/java/com/clearspring/analytics/stream/cardinality/TestHyperLogLog.java
fix test
Java
apache-2.0
0fa19543aa0c4fe84851cc00b0d731260e825739
0
kobejean/tensorflow,gautam1858/tensorflow,zasdfgbnm/tensorflow,girving/tensorflow,davidzchen/tensorflow,AnishShah/tensorflow,cxxgtxy/tensorflow,hfp/tensorflow-xsmm,gunan/tensorflow,paolodedios/tensorflow,Xeralux/tensorflow,zycdragonball/tensorflow,codrut3/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,nolanliou/tensorflow,meteorcloudy/tensorflow,dancingdan/tensorflow,seanli9jan/tensorflow,dongjoon-hyun/tensorflow,dendisuhubdy/tensorflow,ArtsiomCh/tensorflow,tornadozou/tensorflow,ran5515/DeepDecision,jart/tensorflow,renyi533/tensorflow,jalexvig/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow,tiagofrepereira2012/tensorflow,pavelchristof/gomoku-ai,unsiloai/syntaxnet-ops-hack,drpngx/tensorflow,maciekcc/tensorflow,cxxgtxy/tensorflow,jendap/tensorflow,yongtang/tensorflow,aam-at/tensorflow,mavenlin/tensorflow,Mazecreator/tensorflow,dancingdan/tensorflow,horance-liu/tensorflow,manipopopo/tensorflow,dendisuhubdy/tensorflow,benoitsteiner/tensorflow-opencl,arborh/tensorflow,yufengg/tensorflow,ravindrapanda/tensorflow,codrut3/tensorflow,adit-chandra/tensorflow,jendap/tensorflow,av8ramit/tensorflow,jwlawson/tensorflow,eadgarchen/tensorflow,frreiss/tensorflow-fred,ageron/tensorflow,adamtiger/tensorflow,lakshayg/tensorflow,gautam1858/tensorflow,dyoung418/tensorflow,Bulochkin/tensorflow_pack,meteorcloudy/tensorflow,jostep/tensorflow,gunan/tensorflow,jart/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,adamtiger/tensorflow,caisq/tensorflow,Mistobaan/tensorflow,Mazecreator/tensorflow,ppwwyyxx/tensorflow,freedomtan/tensorflow,suiyuan2009/tensorflow,zasdfgbnm/tensorflow,hfp/tensorflow-xsmm,ghchinoy/tensorflow,JingJunYin/tensorflow,gautam1858/tensorflow,arborh/tensorflow,aldian/tensorflow,kevin-coder/tensorflow-fork,gunan/tensorflow,adit-chandra/tensorflow,codrut3/tensorflow,mixturemodel-flow/tensorflow,DavidNorman/tensorflow,Intel-Corporation/tensorflow,aam-at/tensorflow,ran5515/DeepDecision,unsiloai/syntaxnet-ops-hack,theflofly/tensorflow,drpngx/tensorflow,Kongsea/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,hfp/tensorflow-xsmm,kevin-coder/tensorflow-fork,renyi533/tensorflow,tiagofrepereira2012/tensorflow,caisq/tensorflow,girving/tensorflow,lakshayg/tensorflow,davidzchen/tensorflow,horance-liu/tensorflow,asimshankar/tensorflow,andrewcmyers/tensorflow,frreiss/tensorflow-fred,theflofly/tensorflow,nburn42/tensorflow,benoitsteiner/tensorflow-xsmm,yongtang/tensorflow,raymondxyang/tensorflow,unsiloai/syntaxnet-ops-hack,jendap/tensorflow,gojira/tensorflow,renyi533/tensorflow,ghchinoy/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,Bismarrck/tensorflow,meteorcloudy/tensorflow,aselle/tensorflow,theflofly/tensorflow,arborh/tensorflow,lakshayg/tensorflow,drpngx/tensorflow,gunan/tensorflow,codrut3/tensorflow,a-doumoulakis/tensorflow,bowang/tensorflow,tiagofrepereira2012/tensorflow,apark263/tensorflow,eadgarchen/tensorflow,gautam1858/tensorflow,aam-at/tensorflow,jalexvig/tensorflow,drpngx/tensorflow,Intel-tensorflow/tensorflow,nolanliou/tensorflow,sarvex/tensorflow,ghchinoy/tensorflow,raymondxyang/tensorflow,aldian/tensorflow,eaplatanios/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,Mazecreator/tensorflow,tensorflow/tensorflow,drpngx/tensorflow,meteorcloudy/tensorflow,eaplatanios/tensorflow,mdrumond/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jbedorf/tensorflow,tornadozou/tensorflow,ppwwyyxx/tensorflow,brchiu/tensorflow,andrewcmyers/tensorflow,Kongsea/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,jendap/tensorflow,Intel-tensorflow/tensorflow,eaplatanios/tensorflow,dyoung418/tensorflow,yongtang/tensorflow,alsrgv/tensorflow,av8ramit/tensorflow,girving/tensorflow,adit-chandra/tensorflow,ZhangXinNan/tensorflow,benoitsteiner/tensorflow-xsmm,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,alsrgv/tensorflow,with-git/tensorflow,alivecor/tensorflow,annarev/tensorflow,ZhangXinNan/tensorflow,karllessard/tensorflow,aldian/tensorflow,girving/tensorflow,xzturn/tensorflow,codrut3/tensorflow,eadgarchen/tensorflow,zycdragonball/tensorflow,jendap/tensorflow,nburn42/tensorflow,paolodedios/tensorflow,alistairlow/tensorflow,nolanliou/tensorflow,Moriadry/tensorflow,jhseu/tensorflow,benoitsteiner/tensorflow-opencl,jwlawson/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,dongjoon-hyun/tensorflow,tensorflow/tensorflow,adit-chandra/tensorflow,tiagofrepereira2012/tensorflow,jwlawson/tensorflow,gunan/tensorflow,jhseu/tensorflow,asimshankar/tensorflow,Bulochkin/tensorflow_pack,Mistobaan/tensorflow,Xeralux/tensorflow,hfp/tensorflow-xsmm,alsrgv/tensorflow,xodus7/tensorflow,benoitsteiner/tensorflow-xsmm,adit-chandra/tensorflow,jwlawson/tensorflow,guschmue/tensorflow,xzturn/tensorflow,annarev/tensorflow,ZhangXinNan/tensorflow,gautam1858/tensorflow,tiagofrepereira2012/tensorflow,suiyuan2009/tensorflow,lukeiwanski/tensorflow,av8ramit/tensorflow,Mistobaan/tensorflow,petewarden/tensorflow,lukeiwanski/tensorflow,yongtang/tensorflow,benoitsteiner/tensorflow-xsmm,zasdfgbnm/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,Mazecreator/tensorflow,AnishShah/tensorflow,aam-at/tensorflow,AnishShah/tensorflow,arborh/tensorflow,mdrumond/tensorflow,snnn/tensorflow,adit-chandra/tensorflow,sarvex/tensorflow,lukeiwanski/tensorflow,xodus7/tensorflow,Xeralux/tensorflow,dongjoon-hyun/tensorflow,meteorcloudy/tensorflow,chemelnucfin/tensorflow,alshedivat/tensorflow,yongtang/tensorflow,ppwwyyxx/tensorflow,snnn/tensorflow,dyoung418/tensorflow,with-git/tensorflow,gojira/tensorflow,gunan/tensorflow,lukeiwanski/tensorflow,Xeralux/tensorflow,Intel-Corporation/tensorflow,brchiu/tensorflow,asimshankar/tensorflow,drpngx/tensorflow,JVillella/tensorflow,karllessard/tensorflow,laszlocsomor/tensorflow,Xeralux/tensorflow,horance-liu/tensorflow,seanli9jan/tensorflow,hehongliang/tensorflow,lukeiwanski/tensorflow,Kongsea/tensorflow,Intel-tensorflow/tensorflow,kobejean/tensorflow,pavelchristof/gomoku-ai,davidzchen/tensorflow,paolodedios/tensorflow,Bulochkin/tensorflow_pack,ageron/tensorflow,lukeiwanski/tensorflow,guschmue/tensorflow,aam-at/tensorflow,aam-at/tensorflow,benoitsteiner/tensorflow-opencl,snnn/tensorflow,ravindrapanda/tensorflow,ravindrapanda/tensorflow,alivecor/tensorflow,eaplatanios/tensorflow,dongjoon-hyun/tensorflow,yufengg/tensorflow,manazhao/tf_recsys,zasdfgbnm/tensorflow,brchiu/tensorflow,seanli9jan/tensorflow,mixturemodel-flow/tensorflow,adamtiger/tensorflow,girving/tensorflow,eaplatanios/tensorflow,tornadozou/tensorflow,freedomtan/tensorflow,alivecor/tensorflow,AnishShah/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Bismarrck/tensorflow,Intel-tensorflow/tensorflow,yufengg/tensorflow,guschmue/tensorflow,asimshankar/tensorflow,sarvex/tensorflow,renyi533/tensorflow,Kongsea/tensorflow,Xeralux/tensorflow,a-doumoulakis/tensorflow,petewarden/tensorflow,alshedivat/tensorflow,chemelnucfin/tensorflow,ishay2b/tensorflow,laszlocsomor/tensorflow,eadgarchen/tensorflow,hsaputra/tensorflow,alivecor/tensorflow,raymondxyang/tensorflow,Intel-tensorflow/tensorflow,hehongliang/tensorflow,benoitsteiner/tensorflow-xsmm,Bulochkin/tensorflow_pack,ychfan/tensorflow,snnn/tensorflow,jalexvig/tensorflow,raymondxyang/tensorflow,JingJunYin/tensorflow,av8ramit/tensorflow,asimshankar/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,arborh/tensorflow,yufengg/tensorflow,eaplatanios/tensorflow,raymondxyang/tensorflow,dendisuhubdy/tensorflow,mavenlin/tensorflow,Moriadry/tensorflow,petewarden/tensorflow,a-doumoulakis/tensorflow,with-git/tensorflow,Xeralux/tensorflow,aldian/tensorflow,adit-chandra/tensorflow,chemelnucfin/tensorflow,snnn/tensorflow,nburn42/tensorflow,with-git/tensorflow,aselle/tensorflow,av8ramit/tensorflow,nburn42/tensorflow,jbedorf/tensorflow,ychfan/tensorflow,theflofly/tensorflow,Kongsea/tensorflow,hsaputra/tensorflow,ageron/tensorflow,caisq/tensorflow,jhseu/tensorflow,mdrumond/tensorflow,sarvex/tensorflow,brchiu/tensorflow,laszlocsomor/tensorflow,nolanliou/tensorflow,tensorflow/tensorflow,annarev/tensorflow,manipopopo/tensorflow,Intel-Corporation/tensorflow,caisq/tensorflow,a-doumoulakis/tensorflow,DavidNorman/tensorflow,seanli9jan/tensorflow,caisq/tensorflow,Moriadry/tensorflow,aselle/tensorflow,manazhao/tf_recsys,guschmue/tensorflow,ishay2b/tensorflow,alsrgv/tensorflow,annarev/tensorflow,bowang/tensorflow,benoitsteiner/tensorflow-xsmm,DavidNorman/tensorflow,jwlawson/tensorflow,girving/tensorflow,AnishShah/tensorflow,pavelchristof/gomoku-ai,unsiloai/syntaxnet-ops-hack,benoitsteiner/tensorflow-opencl,zycdragonball/tensorflow,Intel-Corporation/tensorflow,jart/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,AnishShah/tensorflow,Xeralux/tensorflow,adamtiger/tensorflow,cxxgtxy/tensorflow,eadgarchen/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tornadozou/tensorflow,xzturn/tensorflow,adit-chandra/tensorflow,manipopopo/tensorflow,dongjoon-hyun/tensorflow,davidzchen/tensorflow,lukeiwanski/tensorflow,kevin-coder/tensorflow-fork,Mistobaan/tensorflow,freedomtan/tensorflow,xodus7/tensorflow,dancingdan/tensorflow,JVillella/tensorflow,av8ramit/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,cxxgtxy/tensorflow,tensorflow/tensorflow,bowang/tensorflow,ageron/tensorflow,dyoung418/tensorflow,jhseu/tensorflow,DavidNorman/tensorflow,Mistobaan/tensorflow,nolanliou/tensorflow,ageron/tensorflow,Moriadry/tensorflow,JVillella/tensorflow,laszlocsomor/tensorflow,jendap/tensorflow,codrut3/tensorflow,xodus7/tensorflow,laszlocsomor/tensorflow,aselle/tensorflow,yufengg/tensorflow,meteorcloudy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,manazhao/tf_recsys,Bulochkin/tensorflow_pack,xodus7/tensorflow,mavenlin/tensorflow,drpngx/tensorflow,jostep/tensorflow,drpngx/tensorflow,manipopopo/tensorflow,jbedorf/tensorflow,dongjoon-hyun/tensorflow,kobejean/tensorflow,xzturn/tensorflow,ZhangXinNan/tensorflow,xzturn/tensorflow,arborh/tensorflow,zasdfgbnm/tensorflow,dancingdan/tensorflow,jalexvig/tensorflow,codrut3/tensorflow,frreiss/tensorflow-fred,jwlawson/tensorflow,petewarden/tensorflow,DavidNorman/tensorflow,mdrumond/tensorflow,alshedivat/tensorflow,lakshayg/tensorflow,alshedivat/tensorflow,kevin-coder/tensorflow-fork,Bulochkin/tensorflow_pack,petewarden/tensorflow,zasdfgbnm/tensorflow,Xeralux/tensorflow,Moriadry/tensorflow,horance-liu/tensorflow,dendisuhubdy/tensorflow,aselle/tensorflow,jostep/tensorflow,gautam1858/tensorflow,dyoung418/tensorflow,gojira/tensorflow,arborh/tensorflow,ArtsiomCh/tensorflow,kobejean/tensorflow,aselle/tensorflow,laszlocsomor/tensorflow,chemelnucfin/tensorflow,karllessard/tensorflow,horance-liu/tensorflow,ychfan/tensorflow,kobejean/tensorflow,jart/tensorflow,xzturn/tensorflow,tornadozou/tensorflow,xzturn/tensorflow,jendap/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,jwlawson/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,freedomtan/tensorflow,horance-liu/tensorflow,andrewcmyers/tensorflow,eadgarchen/tensorflow,chemelnucfin/tensorflow,yanchen036/tensorflow,ravindrapanda/tensorflow,DavidNorman/tensorflow,allenlavoie/tensorflow,freedomtan/tensorflow,hsaputra/tensorflow,chemelnucfin/tensorflow,eadgarchen/tensorflow,ran5515/DeepDecision,dendisuhubdy/tensorflow,alistairlow/tensorflow,paolodedios/tensorflow,codrut3/tensorflow,xodus7/tensorflow,jhseu/tensorflow,horance-liu/tensorflow,gojira/tensorflow,tillahoffmann/tensorflow,mdrumond/tensorflow,allenlavoie/tensorflow,av8ramit/tensorflow,guschmue/tensorflow,JingJunYin/tensorflow,tillahoffmann/tensorflow,benoitsteiner/tensorflow-xsmm,yanchen036/tensorflow,karllessard/tensorflow,ychfan/tensorflow,allenlavoie/tensorflow,mdrumond/tensorflow,alshedivat/tensorflow,yufengg/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,nburn42/tensorflow,benoitsteiner/tensorflow-xsmm,jostep/tensorflow,mixturemodel-flow/tensorflow,snnn/tensorflow,yongtang/tensorflow,maciekcc/tensorflow,manipopopo/tensorflow,alsrgv/tensorflow,ppwwyyxx/tensorflow,ppwwyyxx/tensorflow,Mistobaan/tensorflow,JingJunYin/tensorflow,ZhangXinNan/tensorflow,zasdfgbnm/tensorflow,Kongsea/tensorflow,ran5515/DeepDecision,eaplatanios/tensorflow,karllessard/tensorflow,rabipanda/tensorflow,pavelchristof/gomoku-ai,tensorflow/tensorflow-pywrap_tf_optimizer,gojira/tensorflow,jostep/tensorflow,snnn/tensorflow,ghchinoy/tensorflow,drpngx/tensorflow,yongtang/tensorflow,yanchen036/tensorflow,benoitsteiner/tensorflow-xsmm,AnishShah/tensorflow,alistairlow/tensorflow,jhseu/tensorflow,girving/tensorflow,jbedorf/tensorflow,Mistobaan/tensorflow,xodus7/tensorflow,alivecor/tensorflow,ppwwyyxx/tensorflow,adit-chandra/tensorflow,paolodedios/tensorflow,JVillella/tensorflow,allenlavoie/tensorflow,kevin-coder/tensorflow-fork,Mazecreator/tensorflow,kobejean/tensorflow,kobejean/tensorflow,ravindrapanda/tensorflow,hsaputra/tensorflow,apark263/tensorflow,nburn42/tensorflow,tensorflow/tensorflow-pywrap_saved_model,chemelnucfin/tensorflow,hfp/tensorflow-xsmm,alivecor/tensorflow,aselle/tensorflow,ran5515/DeepDecision,tillahoffmann/tensorflow,jbedorf/tensorflow,renyi533/tensorflow,tornadozou/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,asimshankar/tensorflow,mavenlin/tensorflow,dongjoon-hyun/tensorflow,aselle/tensorflow,jalexvig/tensorflow,alistairlow/tensorflow,mdrumond/tensorflow,alsrgv/tensorflow,ArtsiomCh/tensorflow,zasdfgbnm/tensorflow,jendap/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,rabipanda/tensorflow,Bismarrck/tensorflow,allenlavoie/tensorflow,jendap/tensorflow,dancingdan/tensorflow,DavidNorman/tensorflow,brchiu/tensorflow,with-git/tensorflow,ravindrapanda/tensorflow,paolodedios/tensorflow,a-doumoulakis/tensorflow,jart/tensorflow,jostep/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,manazhao/tf_recsys,tensorflow/tensorflow-pywrap_saved_model,ghchinoy/tensorflow,alivecor/tensorflow,ageron/tensorflow,gojira/tensorflow,seanli9jan/tensorflow,zycdragonball/tensorflow,laszlocsomor/tensorflow,davidzchen/tensorflow,benoitsteiner/tensorflow-xsmm,adit-chandra/tensorflow,mdrumond/tensorflow,hfp/tensorflow-xsmm,jwlawson/tensorflow,annarev/tensorflow,manazhao/tf_recsys,aselle/tensorflow,gunan/tensorflow,lakshayg/tensorflow,with-git/tensorflow,rabipanda/tensorflow,dendisuhubdy/tensorflow,xzturn/tensorflow,jbedorf/tensorflow,kevin-coder/tensorflow-fork,a-doumoulakis/tensorflow,jbedorf/tensorflow,frreiss/tensorflow-fred,theflofly/tensorflow,davidzchen/tensorflow,dancingdan/tensorflow,rabipanda/tensorflow,rabipanda/tensorflow,jhseu/tensorflow,caisq/tensorflow,aldian/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,caisq/tensorflow,ZhangXinNan/tensorflow,frreiss/tensorflow-fred,Bulochkin/tensorflow_pack,andrewcmyers/tensorflow,maciekcc/tensorflow,jart/tensorflow,aselle/tensorflow,dyoung418/tensorflow,zycdragonball/tensorflow,bowang/tensorflow,jart/tensorflow,girving/tensorflow,eaplatanios/tensorflow,xzturn/tensorflow,davidzchen/tensorflow,Mistobaan/tensorflow,hsaputra/tensorflow,hehongliang/tensorflow,allenlavoie/tensorflow,alshedivat/tensorflow,alsrgv/tensorflow,aldian/tensorflow,hfp/tensorflow-xsmm,Bismarrck/tensorflow,dongjoon-hyun/tensorflow,mavenlin/tensorflow,snnn/tensorflow,a-doumoulakis/tensorflow,bowang/tensorflow,tiagofrepereira2012/tensorflow,tensorflow/tensorflow,hfp/tensorflow-xsmm,manipopopo/tensorflow,annarev/tensorflow,Mistobaan/tensorflow,nburn42/tensorflow,freedomtan/tensorflow,chemelnucfin/tensorflow,guschmue/tensorflow,arborh/tensorflow,manipopopo/tensorflow,eadgarchen/tensorflow,apark263/tensorflow,ghchinoy/tensorflow,gunan/tensorflow,tornadozou/tensorflow,Mazecreator/tensorflow,apark263/tensorflow,Bulochkin/tensorflow_pack,arborh/tensorflow,annarev/tensorflow,jhseu/tensorflow,pavelchristof/gomoku-ai,apark263/tensorflow,ychfan/tensorflow,ageron/tensorflow,pavelchristof/gomoku-ai,rabipanda/tensorflow,ychfan/tensorflow,xodus7/tensorflow,maciekcc/tensorflow,ravindrapanda/tensorflow,eaplatanios/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,nolanliou/tensorflow,ghchinoy/tensorflow,tillahoffmann/tensorflow,Bulochkin/tensorflow_pack,frreiss/tensorflow-fred,dendisuhubdy/tensorflow,jart/tensorflow,meteorcloudy/tensorflow,eadgarchen/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,ppwwyyxx/tensorflow,yanchen036/tensorflow,with-git/tensorflow,xodus7/tensorflow,dancingdan/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,theflofly/tensorflow,alistairlow/tensorflow,suiyuan2009/tensorflow,aam-at/tensorflow,renyi533/tensorflow,kevin-coder/tensorflow-fork,JingJunYin/tensorflow,ArtsiomCh/tensorflow,jendap/tensorflow,jhseu/tensorflow,benoitsteiner/tensorflow-xsmm,a-doumoulakis/tensorflow,Kongsea/tensorflow,suiyuan2009/tensorflow,caisq/tensorflow,Bulochkin/tensorflow_pack,av8ramit/tensorflow,ishay2b/tensorflow,freedomtan/tensorflow,rabipanda/tensorflow,horance-liu/tensorflow,ZhangXinNan/tensorflow,bowang/tensorflow,jhseu/tensorflow,alshedivat/tensorflow,nburn42/tensorflow,gunan/tensorflow,benoitsteiner/tensorflow-opencl,with-git/tensorflow,yufengg/tensorflow,renyi533/tensorflow,dongjoon-hyun/tensorflow,ishay2b/tensorflow,ArtsiomCh/tensorflow,freedomtan/tensorflow,ageron/tensorflow,davidzchen/tensorflow,dongjoon-hyun/tensorflow,Bismarrck/tensorflow,jalexvig/tensorflow,yanchen036/tensorflow,unsiloai/syntaxnet-ops-hack,adamtiger/tensorflow,tillahoffmann/tensorflow,brchiu/tensorflow,lukeiwanski/tensorflow,apark263/tensorflow,jendap/tensorflow,andrewcmyers/tensorflow,freedomtan/tensorflow,theflofly/tensorflow,adamtiger/tensorflow,drpngx/tensorflow,gojira/tensorflow,alsrgv/tensorflow,suiyuan2009/tensorflow,theflofly/tensorflow,Bismarrck/tensorflow,Intel-tensorflow/tensorflow,yanchen036/tensorflow,seanli9jan/tensorflow,unsiloai/syntaxnet-ops-hack,girving/tensorflow,petewarden/tensorflow,manipopopo/tensorflow,ghchinoy/tensorflow,yongtang/tensorflow,annarev/tensorflow,jalexvig/tensorflow,jwlawson/tensorflow,ArtsiomCh/tensorflow,karllessard/tensorflow,JingJunYin/tensorflow,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,ZhangXinNan/tensorflow,nolanliou/tensorflow,AnishShah/tensorflow,Mazecreator/tensorflow,jalexvig/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,av8ramit/tensorflow,guschmue/tensorflow,hsaputra/tensorflow,asimshankar/tensorflow,zycdragonball/tensorflow,allenlavoie/tensorflow,seanli9jan/tensorflow,annarev/tensorflow,jbedorf/tensorflow,benoitsteiner/tensorflow-opencl,gunan/tensorflow,aselle/tensorflow,gojira/tensorflow,tensorflow/tensorflow-pywrap_saved_model,laszlocsomor/tensorflow,rabipanda/tensorflow,av8ramit/tensorflow,adit-chandra/tensorflow,rabipanda/tensorflow,gojira/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,rabipanda/tensorflow,laszlocsomor/tensorflow,tensorflow/tensorflow,jbedorf/tensorflow,kobejean/tensorflow,tiagofrepereira2012/tensorflow,alistairlow/tensorflow,av8ramit/tensorflow,alistairlow/tensorflow,alsrgv/tensorflow,dancingdan/tensorflow,pavelchristof/gomoku-ai,benoitsteiner/tensorflow-opencl,zasdfgbnm/tensorflow,allenlavoie/tensorflow,laszlocsomor/tensorflow,JingJunYin/tensorflow,hfp/tensorflow-xsmm,dongjoon-hyun/tensorflow,alistairlow/tensorflow,asimshankar/tensorflow,kevin-coder/tensorflow-fork,raymondxyang/tensorflow,DavidNorman/tensorflow,alsrgv/tensorflow,Intel-tensorflow/tensorflow,codrut3/tensorflow,alshedivat/tensorflow,apark263/tensorflow,JingJunYin/tensorflow,theflofly/tensorflow,asimshankar/tensorflow,renyi533/tensorflow,seanli9jan/tensorflow,nburn42/tensorflow,kevin-coder/tensorflow-fork,dendisuhubdy/tensorflow,xodus7/tensorflow,alsrgv/tensorflow,alshedivat/tensorflow,apark263/tensorflow,andrewcmyers/tensorflow,Moriadry/tensorflow,sarvex/tensorflow,guschmue/tensorflow,tensorflow/tensorflow,ghchinoy/tensorflow,hehongliang/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,seanli9jan/tensorflow,mixturemodel-flow/tensorflow,freedomtan/tensorflow,ArtsiomCh/tensorflow,yanchen036/tensorflow,andrewcmyers/tensorflow,hfp/tensorflow-xsmm,xodus7/tensorflow,maciekcc/tensorflow,zasdfgbnm/tensorflow,manazhao/tf_recsys,brchiu/tensorflow,zasdfgbnm/tensorflow,alshedivat/tensorflow,Moriadry/tensorflow,JVillella/tensorflow,jhseu/tensorflow,Xeralux/tensorflow,brchiu/tensorflow,raymondxyang/tensorflow,dendisuhubdy/tensorflow,ArtsiomCh/tensorflow,caisq/tensorflow,brchiu/tensorflow,ppwwyyxx/tensorflow,allenlavoie/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,andrewcmyers/tensorflow,bowang/tensorflow,DavidNorman/tensorflow,dancingdan/tensorflow,allenlavoie/tensorflow,Mistobaan/tensorflow,jart/tensorflow,ZhangXinNan/tensorflow,gojira/tensorflow,ran5515/DeepDecision,unsiloai/syntaxnet-ops-hack,Mistobaan/tensorflow,adit-chandra/tensorflow,ghchinoy/tensorflow,benoitsteiner/tensorflow-opencl,AnishShah/tensorflow,tensorflow/tensorflow,ageron/tensorflow,jalexvig/tensorflow,chemelnucfin/tensorflow,hfp/tensorflow-xsmm,sarvex/tensorflow,seanli9jan/tensorflow,cxxgtxy/tensorflow,karllessard/tensorflow,alivecor/tensorflow,aam-at/tensorflow,lukeiwanski/tensorflow,asimshankar/tensorflow,manipopopo/tensorflow,bowang/tensorflow,Bismarrck/tensorflow,jwlawson/tensorflow,alistairlow/tensorflow,theflofly/tensorflow,jhseu/tensorflow,gojira/tensorflow,tillahoffmann/tensorflow,lakshayg/tensorflow,Mazecreator/tensorflow,suiyuan2009/tensorflow,ppwwyyxx/tensorflow,nolanliou/tensorflow,alshedivat/tensorflow,kevin-coder/tensorflow-fork,meteorcloudy/tensorflow,Xeralux/tensorflow,jbedorf/tensorflow,petewarden/tensorflow,Mazecreator/tensorflow,xzturn/tensorflow,gunan/tensorflow,Intel-Corporation/tensorflow,eaplatanios/tensorflow,asimshankar/tensorflow,mixturemodel-flow/tensorflow,ZhangXinNan/tensorflow,meteorcloudy/tensorflow,cxxgtxy/tensorflow,lakshayg/tensorflow,hehongliang/tensorflow,Bismarrck/tensorflow,Bismarrck/tensorflow,seanli9jan/tensorflow,freedomtan/tensorflow,JingJunYin/tensorflow,ran5515/DeepDecision,theflofly/tensorflow,renyi533/tensorflow,kobejean/tensorflow,arborh/tensorflow,hsaputra/tensorflow,paolodedios/tensorflow,jostep/tensorflow,adamtiger/tensorflow,davidzchen/tensorflow,lukeiwanski/tensorflow,JVillella/tensorflow,Intel-Corporation/tensorflow,theflofly/tensorflow,ishay2b/tensorflow,nburn42/tensorflow,jalexvig/tensorflow,horance-liu/tensorflow,tornadozou/tensorflow,Bulochkin/tensorflow_pack,jart/tensorflow,ppwwyyxx/tensorflow,jalexvig/tensorflow,jwlawson/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,ZhangXinNan/tensorflow,sarvex/tensorflow,JingJunYin/tensorflow,aldian/tensorflow,mavenlin/tensorflow,ychfan/tensorflow,AnishShah/tensorflow,dyoung418/tensorflow,allenlavoie/tensorflow,petewarden/tensorflow,dancingdan/tensorflow,tillahoffmann/tensorflow,ravindrapanda/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tiagofrepereira2012/tensorflow,chemelnucfin/tensorflow,karllessard/tensorflow,apark263/tensorflow,hsaputra/tensorflow,brchiu/tensorflow,snnn/tensorflow,davidzchen/tensorflow,ychfan/tensorflow,yongtang/tensorflow,hehongliang/tensorflow,DavidNorman/tensorflow,ppwwyyxx/tensorflow,aldian/tensorflow,Bismarrck/tensorflow,tensorflow/tensorflow,hsaputra/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_saved_model,DavidNorman/tensorflow,ravindrapanda/tensorflow,caisq/tensorflow,manazhao/tf_recsys,Bulochkin/tensorflow_pack,ageron/tensorflow,kobejean/tensorflow,yanchen036/tensorflow,maciekcc/tensorflow,pavelchristof/gomoku-ai,rabipanda/tensorflow,renyi533/tensorflow,ychfan/tensorflow,ishay2b/tensorflow,arborh/tensorflow,xzturn/tensorflow,chemelnucfin/tensorflow,chemelnucfin/tensorflow,girving/tensorflow,aam-at/tensorflow,mdrumond/tensorflow,ghchinoy/tensorflow,eaplatanios/tensorflow,meteorcloudy/tensorflow,ppwwyyxx/tensorflow,ghchinoy/tensorflow,jostep/tensorflow,arborh/tensorflow,mavenlin/tensorflow,apark263/tensorflow,alistairlow/tensorflow,lakshayg/tensorflow,Bismarrck/tensorflow,manipopopo/tensorflow,frreiss/tensorflow-fred,ageron/tensorflow,snnn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,eadgarchen/tensorflow,zycdragonball/tensorflow,Moriadry/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,dyoung418/tensorflow,nolanliou/tensorflow,unsiloai/syntaxnet-ops-hack,horance-liu/tensorflow,alsrgv/tensorflow,xzturn/tensorflow,renyi533/tensorflow,petewarden/tensorflow,annarev/tensorflow,renyi533/tensorflow,mixturemodel-flow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,kobejean/tensorflow,jbedorf/tensorflow,apark263/tensorflow,nolanliou/tensorflow,JVillella/tensorflow,maciekcc/tensorflow,mavenlin/tensorflow,freedomtan/tensorflow,gautam1858/tensorflow,ishay2b/tensorflow,hehongliang/tensorflow,codrut3/tensorflow,dancingdan/tensorflow,mixturemodel-flow/tensorflow,guschmue/tensorflow,hsaputra/tensorflow,ageron/tensorflow,Intel-tensorflow/tensorflow,snnn/tensorflow,kevin-coder/tensorflow-fork,AnishShah/tensorflow,benoitsteiner/tensorflow-opencl,suiyuan2009/tensorflow,manipopopo/tensorflow,jbedorf/tensorflow,dendisuhubdy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,brchiu/tensorflow,girving/tensorflow,raymondxyang/tensorflow,nburn42/tensorflow,guschmue/tensorflow,tillahoffmann/tensorflow,mixturemodel-flow/tensorflow,cxxgtxy/tensorflow,aam-at/tensorflow,maciekcc/tensorflow,gunan/tensorflow,Kongsea/tensorflow
// Copyright 2017 The TensorFlow 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.tensorflow.tensorboard.vulcanize; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Verify.verify; import static com.google.common.base.Verify.verifyNotNull; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Splitter; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.javascript.jscomp.BasicErrorManager; import com.google.javascript.jscomp.CheckLevel; import com.google.javascript.jscomp.CompilationLevel; import com.google.javascript.jscomp.Compiler; import com.google.javascript.jscomp.CompilerOptions; import com.google.javascript.jscomp.DiagnosticGroup; import com.google.javascript.jscomp.DiagnosticGroups; import com.google.javascript.jscomp.DiagnosticType; import com.google.javascript.jscomp.JSError; import com.google.javascript.jscomp.ModuleIdentifier; import com.google.javascript.jscomp.PropertyRenamingPolicy; import com.google.javascript.jscomp.Result; import com.google.javascript.jscomp.SourceFile; import com.google.javascript.jscomp.WarningsGuard; import com.google.protobuf.TextFormat; import io.bazel.rules.closure.Webpath; import io.bazel.rules.closure.webfiles.BuildInfo.Webfiles; import io.bazel.rules.closure.webfiles.BuildInfo.WebfilesSource; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.jsoup.Jsoup; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Comment; import org.jsoup.nodes.DataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Html5Printer; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.parser.Parser; import org.jsoup.parser.Tag; /** Simple one-off solution for TensorBoard vulcanization. */ public final class Vulcanize { private static final Pattern IGNORE_PATHS_PATTERN = Pattern.compile("/(?:polymer|marked-element)/.*"); private static final ImmutableSet<String> EXTRA_JSDOC_TAGS = ImmutableSet.of("attribute", "hero", "group", "required"); private static final Pattern WEBPATH_PATTERN = Pattern.compile("//~~WEBPATH~~([^\n]+)"); private static final Parser parser = Parser.htmlParser(); private static final Map<Webpath, Path> webfiles = new HashMap<>(); private static final Set<Webpath> alreadyInlined = new HashSet<>(); private static final Set<String> legalese = new HashSet<>(); private static final List<String> licenses = new ArrayList<>(); private static final List<Webpath> stack = new ArrayList<>(); private static final List<SourceFile> externs = new ArrayList<>(); private static final List<SourceFile> sourcesFromJsLibraries = new ArrayList<>(); private static final Map<Webpath, String> sourcesFromScriptTags = new LinkedHashMap<>(); private static final Map<Webpath, Node> sourceTags = new LinkedHashMap<>(); private static final Multimap<Webpath, String> suppressions = HashMultimap.create(); private static CompilationLevel compilationLevel; private static Webpath outputPath; private static Node firstCompiledScript; private static Node licenseComment; private static int insideDemoSnippet; private static boolean testOnly; public static void main(String[] args) throws IOException { compilationLevel = CompilationLevel.fromString(args[0]); testOnly = args[1].equals("true"); Webpath inputPath = Webpath.get(args[2]); outputPath = Webpath.get(args[3]); Path output = Paths.get(args[4]); for (int i = 5; i < args.length; i++) { if (args[i].endsWith(".js")) { String code = new String(Files.readAllBytes(Paths.get(args[i])), UTF_8); SourceFile sourceFile = SourceFile.fromCode(args[i], code); if (code.contains("@externs")) { externs.add(sourceFile); } else { sourcesFromJsLibraries.add(sourceFile); } continue; } if (!args[i].endsWith(".pbtxt")) { continue; } Webfiles manifest = loadWebfilesPbtxt(Paths.get(args[i])); for (WebfilesSource src : manifest.getSrcList()) { webfiles.put(Webpath.get(src.getWebpath()), Paths.get(src.getPath())); } } stack.add(inputPath); Document document = parse(Files.readAllBytes(webfiles.get(inputPath))); transform(document); compile(); if (licenseComment != null) { licenseComment.attr("comment", String.format("\n%s\n", Joiner.on("\n\n").join(licenses))); } Files.write( output, Html5Printer.stringify(document).getBytes(UTF_8), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } private static void transform(Node root) throws IOException { Node node = checkNotNull(root); Node newNode; while (true) { newNode = enterNode(node); if (node.equals(root)) { root = newNode; } node = newNode; if (node.childNodeSize() > 0) { node = node.childNode(0); } else { while (true) { newNode = leaveNode(node); if (node.equals(root)) { root = newNode; } node = newNode; if (node.equals(root)) { return; } Node next = node.nextSibling(); if (next == null) { if (node.parentNode() == null) { return; } node = verifyNotNull(node.parentNode(), "unexpected root: %s", node); } else { node = next; break; } } } } } private static Node enterNode(Node node) throws IOException { if (node.nodeName().equals("demo-snippet")) { insideDemoSnippet++; } if (insideDemoSnippet > 0) { return node; } if (node instanceof Element) { if (!getAttrTransitive(node, "vulcanize-noinline").isPresent()) { if (node.nodeName().equals("link") && node.attr("rel").equals("import")) { // Inline HTML. node = visitHtmlImport(node); } else if (node.nodeName().equals("script") && !shouldIgnoreUri(node.attr("src")) && !node.hasAttr("jscomp-ignore")) { node = visitScript(node); } else if (node.nodeName().equals("link") && node.attr("rel").equals("stylesheet") && !node.attr("href").isEmpty() && !shouldIgnoreUri(node.attr("href"))) { node = visitStylesheet(node); } } rootifyAttribute(node, "href"); rootifyAttribute(node, "src"); rootifyAttribute(node, "action"); rootifyAttribute(node, "assetpath"); } else if (node instanceof Comment) { String text = ((Comment) node).getData(); if (text.contains("@license")) { handleLicense(text); if (licenseComment == null) { licenseComment = node; } else { node = replaceNode(node, new TextNode("", node.baseUri())); } } else { node = replaceNode(node, new TextNode("", node.baseUri())); } } return node; } private static Node leaveNode(Node node) { if (node instanceof Document) { stack.remove(stack.size() - 1); } else if (node.nodeName().equals("demo-snippet")) { insideDemoSnippet--; } return node; } private static Node visitHtmlImport(Node node) throws IOException { Webpath href = me().lookup(Webpath.get(node.attr("href"))); if (alreadyInlined.add(href)) { stack.add(href); Document subdocument = parse(Files.readAllBytes(getWebfile(href))); for (Attribute attr : node.attributes()) { subdocument.attr(attr.getKey(), attr.getValue()); } return replaceNode(node, subdocument); } else { return replaceNode(node, new TextNode("", node.baseUri())); } } private static Node visitScript(Node node) throws IOException { Webpath path; String script; if (node.attr("src").isEmpty()) { path = makeSyntheticName(".js"); script = getInlineScriptFromNode(node); } else { path = me().lookup(Webpath.get(node.attr("src"))); script = new String(Files.readAllBytes(getWebfile(path)), UTF_8); } boolean wantsMinify = getAttrTransitive(node, "jscomp-minify").isPresent(); if (node.attr("src").endsWith(".min.js") || getAttrTransitive(node, "jscomp-nocompile").isPresent() || wantsMinify) { if (wantsMinify) { script = minify(path, script); } Node newScript = new Element(Tag.valueOf("script"), node.baseUri(), node.attributes()) .appendChild(new DataNode(script, node.baseUri())) .removeAttr("src") .removeAttr("jscomp-minify") .removeAttr("jscomp-nocompile"); if (firstCompiledScript != null) { firstCompiledScript.before(newScript); return replaceNode(node, new TextNode("", node.baseUri())); } else { return replaceNode(node, newScript); } } else { if (firstCompiledScript == null) { firstCompiledScript = node; } sourcesFromScriptTags.put(path, script); sourceTags.put(path, node); Optional<String> suppress = getAttrTransitive(node, "jscomp-suppress"); if (suppress.isPresent()) { if (suppress.get().isEmpty()) { suppressions.put(path, "*"); } else { suppressions.putAll(path, Splitter.on(' ').split(suppress.get())); } } return node; } } private static Node visitStylesheet(Node node) throws IOException { Webpath href = me().lookup(Webpath.get(node.attr("href"))); return replaceNode( node, new Element(Tag.valueOf("style"), node.baseUri(), node.attributes()) .appendChild( new DataNode( new String(Files.readAllBytes(getWebfile(href)), UTF_8), node.baseUri())) .removeAttr("rel") .removeAttr("href")); } private static Optional<String> getAttrTransitive(Node node, String attr) { while (node != null) { if (node.hasAttr(attr)) { return Optional.of(node.attr(attr)); } node = node.parent(); } return Optional.absent(); } private static Node replaceNode(Node oldNode, Node newNode) { oldNode.replaceWith(newNode); return newNode; } private static Path getWebfile(Webpath path) { return verifyNotNull(webfiles.get(path), "Bad ref: %s -> %s", me(), path); } private static void compile() { if (sourcesFromScriptTags.isEmpty()) { return; } CompilerOptions options = new CompilerOptions(); compilationLevel.setOptionsForCompilationLevel(options); // Nice options. options.setColorizeErrorOutput(true); options.setContinueAfterErrors(true); options.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT_2016); options.setLanguageOut(CompilerOptions.LanguageMode.ECMASCRIPT5); options.setGenerateExports(true); options.setStrictModeInput(false); options.setExtraAnnotationNames(EXTRA_JSDOC_TAGS); // So we can chop JS binary back up into the original script tags. options.setPrintInputDelimiter(true); options.setInputDelimiter("//~~WEBPATH~~%name%"); // Optimizations that are too advanced for us right now. options.setPropertyRenaming(PropertyRenamingPolicy.OFF); options.setCheckGlobalThisLevel(CheckLevel.OFF); options.setRemoveUnusedPrototypeProperties(false); options.setRemoveUnusedPrototypePropertiesInExterns(false); options.setRemoveUnusedClassProperties(false); // Dependency management. options.setClosurePass(true); options.setManageClosureDependencies(true); options.getDependencyOptions().setDependencyPruning(true); options.getDependencyOptions().setDependencySorting(true); options.getDependencyOptions().setMoocherDropping(false); options.getDependencyOptions() .setEntryPoints( sourceTags .keySet() .stream() .map(Webpath::toString) .map(ModuleIdentifier::forFile) .collect(Collectors.toList())); // Polymer pass. options.setPolymerVersion(1); // Debug flags. if (testOnly) { options.setPrettyPrint(true); options.setGeneratePseudoNames(true); options.setExportTestFunctions(true); } // Don't print warnings from <script jscomp-suppress="group1 group2" ...> tags. ImmutableMultimap<DiagnosticType, String> diagnosticGroups = initDiagnosticGroups(); options.addWarningsGuard( new WarningsGuard() { @Override public CheckLevel level(JSError error) { if (error.sourceName == null) { return null; } if (error.sourceName.startsWith("javascript/externs") || error.sourceName.contains("com_google_javascript_closure_compiler_externs")) { // TODO(jart): Figure out why these "mismatch of the removeEventListener property on // type" warnings are showing up. // https://github.com/google/closure-compiler/pull/1959 return CheckLevel.OFF; } if (IGNORE_PATHS_PATTERN.matcher(error.sourceName).matches()) { return CheckLevel.OFF; } if (error.sourceName.startsWith("/tf-graph") && error.getType().key.equals("JSC_VAR_MULTIPLY_DECLARED_ERROR")) { return CheckLevel.OFF; // TODO(jart): Remove when tf-graph is ES6 modules. } if (error.getType().key.equals("JSC_POLYMER_UNQUALIFIED_BEHAVIOR") || error.getType().key.equals("JSC_POLYMER_UNANNOTATED_BEHAVIOR")) { return CheckLevel.OFF; // TODO(jart): What is wrong with this thing? } Collection<String> codes = suppressions.get(Webpath.get(error.sourceName)); if (codes.contains("*") || codes.contains(error.getType().key)) { return CheckLevel.OFF; } for (String group : diagnosticGroups.get(error.getType())) { if (codes.contains(group)) { return CheckLevel.OFF; } } return null; } }); // Get reverse topological script tags and their web paths, which js_library stuff first. List<SourceFile> sauce = Lists.newArrayList(sourcesFromJsLibraries); for (Map.Entry<Webpath, String> source : sourcesFromScriptTags.entrySet()) { sauce.add(SourceFile.fromCode(source.getKey().toString(), source.getValue())); } // Compile everything into a single script. Compiler compiler = new Compiler(); compiler.disableThreads(); Result result = compiler.compile(externs, sauce, options); if (!result.success) { System.exit(1); } String jsBlob = compiler.toSource(); // Split apart the JS blob and put it back in the original <script> locations. Deque<Map.Entry<Webpath, Node>> tags = new ArrayDeque<>(); tags.addAll(sourceTags.entrySet()); Matcher matcher = WEBPATH_PATTERN.matcher(jsBlob); verify(matcher.find(), "Nothing found in compiled JS blob!"); Webpath path = Webpath.get(matcher.group(1)); int start = 0; while (matcher.find()) { if (sourceTags.containsKey(path)) { swapScript(tags, path, jsBlob.substring(start, matcher.start())); start = matcher.start(); } path = Webpath.get(matcher.group(1)); } swapScript(tags, path, jsBlob.substring(start)); verify(tags.isEmpty(), "<script> wasn't compiled: %s", tags); } private static void swapScript( Deque<Map.Entry<Webpath, Node>> tags, Webpath path, String script) { verify(!tags.isEmpty(), "jscomp compiled %s after last <script>?!", path); Webpath want = tags.getFirst().getKey(); verify(path.equals(want), "<script> tag for %s should come before %s", path, want); Node tag = tags.removeFirst().getValue(); tag.replaceWith( new Element(Tag.valueOf("script"), tag.baseUri()) .appendChild(new DataNode(script, tag.baseUri()))); } private static String minify(Webpath path, String script) { CompilerOptions options = new CompilerOptions(); options.skipAllCompilerPasses(); options.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT_2016); options.setLanguageOut(CompilerOptions.LanguageMode.ECMASCRIPT5); options.setContinueAfterErrors(true); CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options); if (testOnly) { options.setPrettyPrint(true); options.setGeneratePseudoNames(true); } Compiler compiler = new Compiler(new JsPrintlessErrorManager()); compiler.disableThreads(); compiler.compile( ImmutableList.<SourceFile>of(), ImmutableList.of(SourceFile.fromCode(path.toString(), script)), options); return compiler.toSource(); } private static void handleLicense(String text) { if (legalese.add(CharMatcher.whitespace().removeFrom(text))) { licenses.add(CharMatcher.anyOf("\r\n").trimFrom(text)); } } private static Webpath me() { return Iterables.getLast(stack); } private static Webpath makeSyntheticName(String extension) { String me = me().toString(); Webpath result = Webpath.get(me + extension); int n = 2; while (sourcesFromScriptTags.containsKey(result)) { result = Webpath.get(String.format("%s-%d%s", me, n++, extension)); } return result; } private static void rootifyAttribute(Node node, String attribute) { String value = node.attr(attribute); if (value.isEmpty()) { return; } Webpath uri = Webpath.get(value); if (webfiles.containsKey(uri)) { node.attr(attribute, outputPath.getParent().relativize(uri).toString()); } } private static String getInlineScriptFromNode(Node node) { StringBuilder sb = new StringBuilder(); for (Node child : node.childNodes()) { if (child instanceof DataNode) { sb.append(((DataNode) child).getWholeData()); } } return sb.toString(); } private static Document parse(byte[] bytes) { return parse(new ByteArrayInputStream(bytes)); } private static Document parse(InputStream input) { Document document; try { document = Jsoup.parse(input, null, "", parser); } catch (IOException e) { throw new AssertionError("I/O error when parsing byte array D:", e); } document.outputSettings().indentAmount(0); document.outputSettings().prettyPrint(false); return document; } private static Webfiles loadWebfilesPbtxt(Path path) throws IOException { verify(path.toString().endsWith(".pbtxt"), "Not a pbtxt file: %s", path); Webfiles.Builder build = Webfiles.newBuilder(); TextFormat.getParser().merge(new String(Files.readAllBytes(path), UTF_8), build); return build.build(); } private static boolean shouldIgnoreUri(String uri) { return uri.startsWith("#") || uri.endsWith("/") || uri.contains("//") || uri.startsWith("data:") || uri.startsWith("javascript:") // The following are intended to filter out URLs with Polymer variables. || (uri.contains("[[") && uri.contains("]]")) || (uri.contains("{{") && uri.contains("}}")); } private static ImmutableMultimap<DiagnosticType, String> initDiagnosticGroups() { DiagnosticGroups groups = new DiagnosticGroups(); Multimap<DiagnosticType, String> builder = HashMultimap.create(); for (Map.Entry<String, DiagnosticGroup> group : groups.getRegisteredGroups().entrySet()) { for (DiagnosticType type : group.getValue().getTypes()) { builder.put(type, group.getKey()); } } return ImmutableMultimap.copyOf(builder); } private static final class JsPrintlessErrorManager extends BasicErrorManager { @Override public void println(CheckLevel level, JSError error) {} @Override public void printSummary() {} } }
tensorflow/tensorboard/java/org/tensorflow/tensorboard/vulcanize/Vulcanize.java
// Copyright 2017 The TensorFlow 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.tensorflow.tensorboard.vulcanize; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Verify.verify; import static com.google.common.base.Verify.verifyNotNull; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Splitter; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.javascript.jscomp.CheckLevel; import com.google.javascript.jscomp.CompilationLevel; import com.google.javascript.jscomp.Compiler; import com.google.javascript.jscomp.CompilerOptions; import com.google.javascript.jscomp.DiagnosticGroup; import com.google.javascript.jscomp.DiagnosticGroups; import com.google.javascript.jscomp.DiagnosticType; import com.google.javascript.jscomp.JSError; import com.google.javascript.jscomp.ModuleIdentifier; import com.google.javascript.jscomp.PropertyRenamingPolicy; import com.google.javascript.jscomp.Result; import com.google.javascript.jscomp.SourceFile; import com.google.javascript.jscomp.WarningsGuard; import com.google.protobuf.TextFormat; import io.bazel.rules.closure.Webpath; import io.bazel.rules.closure.webfiles.BuildInfo.Webfiles; import io.bazel.rules.closure.webfiles.BuildInfo.WebfilesSource; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.jsoup.Jsoup; import org.jsoup.nodes.Attribute; import org.jsoup.nodes.Comment; import org.jsoup.nodes.DataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Html5Printer; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.parser.Parser; import org.jsoup.parser.Tag; /** Simple one-off solution for TensorBoard vulcanization. */ public final class Vulcanize { private static final Pattern IGNORE_PATHS_PATTERN = Pattern.compile("/(?:polymer|marked-element)/.*"); private static final ImmutableSet<String> EXTRA_JSDOC_TAGS = ImmutableSet.of("attribute", "hero", "group", "required"); private static final Pattern WEBPATH_PATTERN = Pattern.compile("//~~WEBPATH~~([^\n]+)"); private static final Parser parser = Parser.htmlParser(); private static final Map<Webpath, Path> webfiles = new HashMap<>(); private static final Set<Webpath> alreadyInlined = new HashSet<>(); private static final Set<String> legalese = new HashSet<>(); private static final List<String> licenses = new ArrayList<>(); private static final List<Webpath> stack = new ArrayList<>(); private static final List<SourceFile> externs = new ArrayList<>(); private static final List<SourceFile> sourcesFromJsLibraries = new ArrayList<>(); private static final Map<Webpath, String> sourcesFromScriptTags = new LinkedHashMap<>(); private static final Map<Webpath, Node> sourceTags = new LinkedHashMap<>(); private static final Multimap<Webpath, String> suppressions = HashMultimap.create(); private static CompilationLevel compilationLevel; private static Webpath outputPath; private static Node firstCompiledScript; private static Node licenseComment; private static int insideDemoSnippet; private static boolean testOnly; public static void main(String[] args) throws IOException { compilationLevel = CompilationLevel.fromString(args[0]); testOnly = args[1].equals("true"); Webpath inputPath = Webpath.get(args[2]); outputPath = Webpath.get(args[3]); Path output = Paths.get(args[4]); for (int i = 5; i < args.length; i++) { if (args[i].endsWith(".js")) { String code = new String(Files.readAllBytes(Paths.get(args[i])), UTF_8); SourceFile sourceFile = SourceFile.fromCode(args[i], code); if (code.contains("@externs")) { externs.add(sourceFile); } else { sourcesFromJsLibraries.add(sourceFile); } continue; } if (!args[i].endsWith(".pbtxt")) { continue; } Webfiles manifest = loadWebfilesPbtxt(Paths.get(args[i])); for (WebfilesSource src : manifest.getSrcList()) { webfiles.put(Webpath.get(src.getWebpath()), Paths.get(src.getPath())); } } stack.add(inputPath); Document document = parse(Files.readAllBytes(webfiles.get(inputPath))); transform(document); compile(); if (licenseComment != null) { licenseComment.attr("comment", String.format("\n%s\n", Joiner.on("\n\n").join(licenses))); } Files.write( output, Html5Printer.stringify(document).getBytes(UTF_8), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } private static void transform(Node root) throws IOException { Node node = checkNotNull(root); Node newNode; while (true) { newNode = enterNode(node); if (node.equals(root)) { root = newNode; } node = newNode; if (node.childNodeSize() > 0) { node = node.childNode(0); } else { while (true) { newNode = leaveNode(node); if (node.equals(root)) { root = newNode; } node = newNode; if (node.equals(root)) { return; } Node next = node.nextSibling(); if (next == null) { if (node.parentNode() == null) { return; } node = verifyNotNull(node.parentNode(), "unexpected root: %s", node); } else { node = next; break; } } } } } private static Node enterNode(Node node) throws IOException { if (node.nodeName().equals("demo-snippet")) { insideDemoSnippet++; } if (insideDemoSnippet > 0) { return node; } if (node instanceof Element) { if (!getAttrTransitive(node, "vulcanize-noinline").isPresent()) { if (node.nodeName().equals("link") && node.attr("rel").equals("import")) { // Inline HTML. node = visitHtmlImport(node); } else if (node.nodeName().equals("script") && !shouldIgnoreUri(node.attr("src")) && !node.hasAttr("jscomp-ignore")) { node = visitScript(node); } else if (node.nodeName().equals("link") && node.attr("rel").equals("stylesheet") && !node.attr("href").isEmpty() && !shouldIgnoreUri(node.attr("href"))) { node = visitStylesheet(node); } } rootifyAttribute(node, "href"); rootifyAttribute(node, "src"); rootifyAttribute(node, "action"); rootifyAttribute(node, "assetpath"); } else if (node instanceof Comment) { String text = ((Comment) node).getData(); if (text.contains("@license")) { handleLicense(text); if (licenseComment == null) { licenseComment = node; } else { node = replaceNode(node, new TextNode("", node.baseUri())); } } else { node = replaceNode(node, new TextNode("", node.baseUri())); } } return node; } private static Node leaveNode(Node node) { if (node instanceof Document) { stack.remove(stack.size() - 1); } else if (node.nodeName().equals("demo-snippet")) { insideDemoSnippet--; } return node; } private static Node visitHtmlImport(Node node) throws IOException { Webpath href = me().lookup(Webpath.get(node.attr("href"))); if (alreadyInlined.add(href)) { stack.add(href); Document subdocument = parse(Files.readAllBytes(getWebfile(href))); for (Attribute attr : node.attributes()) { subdocument.attr(attr.getKey(), attr.getValue()); } return replaceNode(node, subdocument); } else { return replaceNode(node, new TextNode("", node.baseUri())); } } private static Node visitScript(Node node) throws IOException { Webpath path; String script; if (node.attr("src").isEmpty()) { path = makeSyntheticName(".js"); script = getInlineScriptFromNode(node); } else { path = me().lookup(Webpath.get(node.attr("src"))); script = new String(Files.readAllBytes(getWebfile(path)), UTF_8); } boolean wantsMinify = getAttrTransitive(node, "jscomp-minify").isPresent(); if (node.attr("src").endsWith(".min.js") || getAttrTransitive(node, "jscomp-nocompile").isPresent() || wantsMinify) { if (wantsMinify) { script = minify(path, script); } Node newScript = new Element(Tag.valueOf("script"), node.baseUri(), node.attributes()) .appendChild(new DataNode(script, node.baseUri())) .removeAttr("src") .removeAttr("jscomp-minify") .removeAttr("jscomp-nocompile"); if (firstCompiledScript != null) { firstCompiledScript.before(newScript); return replaceNode(node, new TextNode("", node.baseUri())); } else { return replaceNode(node, newScript); } } else { if (firstCompiledScript == null) { firstCompiledScript = node; } sourcesFromScriptTags.put(path, script); sourceTags.put(path, node); Optional<String> suppress = getAttrTransitive(node, "jscomp-suppress"); if (suppress.isPresent()) { if (suppress.get().isEmpty()) { suppressions.put(path, "*"); } else { suppressions.putAll(path, Splitter.on(' ').split(suppress.get())); } } return node; } } private static Node visitStylesheet(Node node) throws IOException { Webpath href = me().lookup(Webpath.get(node.attr("href"))); return replaceNode( node, new Element(Tag.valueOf("style"), node.baseUri(), node.attributes()) .appendChild( new DataNode( new String(Files.readAllBytes(getWebfile(href)), UTF_8), node.baseUri())) .removeAttr("rel") .removeAttr("href")); } private static Optional<String> getAttrTransitive(Node node, String attr) { while (node != null) { if (node.hasAttr(attr)) { return Optional.of(node.attr(attr)); } node = node.parent(); } return Optional.absent(); } private static Node replaceNode(Node oldNode, Node newNode) { oldNode.replaceWith(newNode); return newNode; } private static Path getWebfile(Webpath path) { return verifyNotNull(webfiles.get(path), "Bad ref: %s -> %s", me(), path); } private static void compile() { if (sourcesFromScriptTags.isEmpty()) { return; } CompilerOptions options = new CompilerOptions(); compilationLevel.setOptionsForCompilationLevel(options); // Nice options. options.setColorizeErrorOutput(true); options.setContinueAfterErrors(true); options.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT_2016); options.setLanguageOut(CompilerOptions.LanguageMode.ECMASCRIPT5); options.setGenerateExports(true); options.setStrictModeInput(false); options.setExtraAnnotationNames(EXTRA_JSDOC_TAGS); // So we can chop JS binary back up into the original script tags. options.setPrintInputDelimiter(true); options.setInputDelimiter("//~~WEBPATH~~%name%"); // Optimizations that are too advanced for us right now. options.setPropertyRenaming(PropertyRenamingPolicy.OFF); options.setCheckGlobalThisLevel(CheckLevel.OFF); options.setRemoveUnusedPrototypeProperties(false); options.setRemoveUnusedPrototypePropertiesInExterns(false); options.setRemoveUnusedClassProperties(false); // Dependency management. options.setClosurePass(true); options.setManageClosureDependencies(true); options.getDependencyOptions().setDependencyPruning(true); options.getDependencyOptions().setDependencySorting(true); options.getDependencyOptions().setMoocherDropping(false); options.getDependencyOptions() .setEntryPoints( sourceTags .keySet() .stream() .map(Webpath::toString) .map(ModuleIdentifier::forFile) .collect(Collectors.toList())); // Polymer pass. options.setPolymerVersion(1); // Debug flags. if (testOnly) { options.setPrettyPrint(true); options.setGeneratePseudoNames(true); options.setExportTestFunctions(true); } // Don't print warnings from <script jscomp-suppress="group1 group2" ...> tags. ImmutableMultimap<DiagnosticType, String> diagnosticGroups = initDiagnosticGroups(); options.addWarningsGuard( new WarningsGuard() { @Override public CheckLevel level(JSError error) { if (error.sourceName == null) { return null; } if (error.sourceName.startsWith("javascript/externs") || error.sourceName.contains("com_google_javascript_closure_compiler_externs")) { // TODO(jart): Figure out why these "mismatch of the removeEventListener property on // type" warnings are showing up. // https://github.com/google/closure-compiler/pull/1959 return CheckLevel.OFF; } if (IGNORE_PATHS_PATTERN.matcher(error.sourceName).matches()) { return CheckLevel.OFF; } if (error.sourceName.startsWith("/tf-graph") && error.getType().key.equals("JSC_VAR_MULTIPLY_DECLARED_ERROR")) { return CheckLevel.OFF; // TODO(jart): Remove when tf-graph is ES6 modules. } if (error.getType().key.equals("JSC_POLYMER_UNQUALIFIED_BEHAVIOR") || error.getType().key.equals("JSC_POLYMER_UNANNOTATED_BEHAVIOR")) { return CheckLevel.OFF; // TODO(jart): What is wrong with this thing? } Collection<String> codes = suppressions.get(Webpath.get(error.sourceName)); if (codes.contains("*") || codes.contains(error.getType().key)) { return CheckLevel.OFF; } for (String group : diagnosticGroups.get(error.getType())) { if (codes.contains(group)) { return CheckLevel.OFF; } } return null; } }); // Get reverse topological script tags and their web paths, which js_library stuff first. List<SourceFile> sauce = Lists.newArrayList(sourcesFromJsLibraries); for (Map.Entry<Webpath, String> source : sourcesFromScriptTags.entrySet()) { sauce.add(SourceFile.fromCode(source.getKey().toString(), source.getValue())); } // Compile everything into a single script. Compiler compiler = new Compiler(); compiler.disableThreads(); Result result = compiler.compile(externs, sauce, options); if (!result.success) { System.exit(1); } String jsBlob = compiler.toSource(); // Split apart the JS blob and put it back in the original <script> locations. Deque<Map.Entry<Webpath, Node>> tags = new ArrayDeque<>(); tags.addAll(sourceTags.entrySet()); Matcher matcher = WEBPATH_PATTERN.matcher(jsBlob); verify(matcher.find(), "Nothing found in compiled JS blob!"); Webpath path = Webpath.get(matcher.group(1)); int start = 0; while (matcher.find()) { if (sourceTags.containsKey(path)) { swapScript(tags, path, jsBlob.substring(start, matcher.start())); start = matcher.start(); } path = Webpath.get(matcher.group(1)); } swapScript(tags, path, jsBlob.substring(start)); verify(tags.isEmpty(), "<script> wasn't compiled: %s", tags); } private static void swapScript( Deque<Map.Entry<Webpath, Node>> tags, Webpath path, String script) { verify(!tags.isEmpty(), "jscomp compiled %s after last <script>?!", path); Webpath want = tags.getFirst().getKey(); verify(path.equals(want), "<script> tag for %s should come before %s", path, want); Node tag = tags.removeFirst().getValue(); tag.replaceWith( new Element(Tag.valueOf("script"), tag.baseUri()) .appendChild(new DataNode(script, tag.baseUri()))); } private static String minify(Webpath path, String script) { CompilerOptions options = new CompilerOptions(); options.skipAllCompilerPasses(); options.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT_2016); options.setLanguageOut(CompilerOptions.LanguageMode.ECMASCRIPT5); options.setContinueAfterErrors(true); CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options); if (testOnly) { options.setPrettyPrint(true); options.setGeneratePseudoNames(true); } Compiler compiler = new Compiler(); compiler.disableThreads(); compiler.compile( ImmutableList.<SourceFile>of(), ImmutableList.of(SourceFile.fromCode(path.toString(), script)), options); return compiler.toSource(); } private static void handleLicense(String text) { if (legalese.add(CharMatcher.whitespace().removeFrom(text))) { licenses.add(CharMatcher.anyOf("\r\n").trimFrom(text)); } } private static Webpath me() { return Iterables.getLast(stack); } private static Webpath makeSyntheticName(String extension) { String me = me().toString(); Webpath result = Webpath.get(me + extension); int n = 2; while (sourcesFromScriptTags.containsKey(result)) { result = Webpath.get(String.format("%s-%d%s", me, n++, extension)); } return result; } private static void rootifyAttribute(Node node, String attribute) { String value = node.attr(attribute); if (value.isEmpty()) { return; } Webpath uri = Webpath.get(value); if (webfiles.containsKey(uri)) { node.attr(attribute, outputPath.getParent().relativize(uri).toString()); } } private static String getInlineScriptFromNode(Node node) { StringBuilder sb = new StringBuilder(); for (Node child : node.childNodes()) { if (child instanceof DataNode) { sb.append(((DataNode) child).getWholeData()); } } return sb.toString(); } private static Document parse(byte[] bytes) { return parse(new ByteArrayInputStream(bytes)); } private static Document parse(InputStream input) { Document document; try { document = Jsoup.parse(input, null, "", parser); } catch (IOException e) { throw new AssertionError("I/O error when parsing byte array D:", e); } document.outputSettings().indentAmount(0); document.outputSettings().prettyPrint(false); return document; } private static Webfiles loadWebfilesPbtxt(Path path) throws IOException { verify(path.toString().endsWith(".pbtxt"), "Not a pbtxt file: %s", path); Webfiles.Builder build = Webfiles.newBuilder(); TextFormat.getParser().merge(new String(Files.readAllBytes(path), UTF_8), build); return build.build(); } private static boolean shouldIgnoreUri(String uri) { return uri.startsWith("#") || uri.endsWith("/") || uri.contains("//") || uri.startsWith("data:") || uri.startsWith("javascript:") // The following are intended to filter out URLs with Polymer variables. || (uri.contains("[[") && uri.contains("]]")) || (uri.contains("{{") && uri.contains("}}")); } private static ImmutableMultimap<DiagnosticType, String> initDiagnosticGroups() { DiagnosticGroups groups = new DiagnosticGroups(); Multimap<DiagnosticType, String> builder = HashMultimap.create(); for (Map.Entry<String, DiagnosticGroup> group : groups.getRegisteredGroups().entrySet()) { for (DiagnosticType type : group.getValue().getTypes()) { builder.put(type, group.getKey()); } } return ImmutableMultimap.copyOf(builder); } }
Make JS minifier not print warnings PiperOrigin-RevId: 159045577
tensorflow/tensorboard/java/org/tensorflow/tensorboard/vulcanize/Vulcanize.java
Make JS minifier not print warnings
Java
apache-2.0
10b95ad2e355fd8ede4fac885647a48f66717b5e
0
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
/* * JaamSim Discrete Event Simulation * Copyright (C) 2015 Ausenco Engineering Canada Inc. * Copyright (C) 2017-2018 JaamSim Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaamsim.StringProviders; import java.util.ArrayList; import java.util.Collections; import com.jaamsim.Samples.SampleProvider; import com.jaamsim.basicsim.Entity; import com.jaamsim.basicsim.JaamSimModel; import com.jaamsim.input.Input; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.KeywordIndex; import com.jaamsim.input.ListInput; import com.jaamsim.units.Unit; public class StringProvListInput extends ListInput<ArrayList<StringProvider>> { private ArrayList<Class<? extends Unit>> unitTypeList; public StringProvListInput(String key, String cat, ArrayList<StringProvider> def) { super(key, cat, def); } public void setUnitTypeList(ArrayList<Class<? extends Unit>> utList) { if (utList.equals(unitTypeList)) return; unitTypeList = new ArrayList<>(utList); this.setValid(false); } public void setUnitType(Class<? extends Unit> u) { ArrayList<Class<? extends Unit>> utList = new ArrayList<>(1); utList.add(u); this.setUnitTypeList(utList); } /** * Returns the unit type for the specified expression. * <p> * If the number of expressions exceeds the number of unit types * then the last unit type in the list is returned. * @param i - index of the expression * @return unit type for the expression */ public Class<? extends Unit> getUnitType(int i) { if (unitTypeList.isEmpty()) return null; int k = Math.min(i, unitTypeList.size()-1); return unitTypeList.get(k); } @Override public int getListSize() { if (value == null) return 0; else return value.size(); } @Override public void copyFrom(Entity thisEnt, Input<?> in) { super.copyFrom(thisEnt, in); // An expression input must be re-parsed to reset the entity referred to by "this" parseFrom(thisEnt, in); } @Override public void parse(Entity thisEnt, KeywordIndex kw) throws InputErrorException { ArrayList<KeywordIndex> subArgs = kw.getSubArgs(); ArrayList<StringProvider> temp = new ArrayList<>(subArgs.size()); for (int i = 0; i < subArgs.size(); i++) { KeywordIndex subArg = subArgs.get(i); try { StringProvider sp = Input.parseStringProvider(subArg, thisEnt, getUnitType(i)); temp.add(sp); } catch (InputErrorException e) { if (subArgs.size() == 1) throw new InputErrorException(e.getMessage()); else throw new InputErrorException(INP_ERR_ELEMENT, i+1, e.getMessage()); } } value = temp; this.setValid(true); } @Override public String getValidInputDesc() { return Input.VALID_STRING_PROV_LIST; } @Override public ArrayList<String> getValidOptions(Entity ent) { ArrayList<String> list = new ArrayList<>(); JaamSimModel simModel = ent.getJaamSimModel(); for (Entity each : simModel.getClonesOfIterator(Entity.class, SampleProvider.class)) { SampleProvider samp = (SampleProvider)each; if (unitTypeList.contains(samp.getUnitType())) list.add(each.getName()); } Collections.sort(list, Input.uiSortOrder); return list; } @Override public void getValueTokens(ArrayList<String> toks) { if (value == null) return; for (int i = 0; i < value.size(); i++) { toks.add("{"); toks.add(value.get(i).toString()); toks.add("}"); } } @Override public String getDefaultString() { if (defValue == null || defValue.isEmpty()) { return ""; } StringBuilder tmp = new StringBuilder(); for (int i = 0; i < defValue.size(); i++) { if (i > 0) tmp.append(SEPARATOR); tmp.append("{ "); tmp.append(defValue.get(i)); tmp.append(" }"); } return tmp.toString(); } @Override public boolean removeReferences(Entity ent) { if (value == null) return false; ArrayList<StringProvider> list = new ArrayList<>(); for (StringProvider samp : value) { if (samp instanceof StringProvSample) { StringProvSample spsamp = (StringProvSample) samp; if (spsamp.getSampleProvider() == ent) { list.add(samp); } } } boolean ret = value.removeAll(list); return ret; } @Override public boolean useExpressionBuilder() { return true; } @Override public String getPresentValueString(double simTime) { if (value == null) return ""; StringBuilder sb = new StringBuilder(); boolean first = true; for (int i = 0; i < value.size(); i++) { StringProvider prov = value.get(i); if (!first) { first = false; } else { sb.append(Input.SEPARATOR); } sb.append("{").append(Input.BRACE_SEPARATOR); sb.append(prov.getNextString(simTime)); sb.append(Input.BRACE_SEPARATOR).append("}"); } return sb.toString(); } }
src/main/java/com/jaamsim/StringProviders/StringProvListInput.java
/* * JaamSim Discrete Event Simulation * Copyright (C) 2015 Ausenco Engineering Canada Inc. * Copyright (C) 2017-2018 JaamSim Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaamsim.StringProviders; import java.util.ArrayList; import java.util.Collections; import com.jaamsim.Samples.SampleProvider; import com.jaamsim.basicsim.Entity; import com.jaamsim.basicsim.JaamSimModel; import com.jaamsim.input.Input; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.KeywordIndex; import com.jaamsim.input.ListInput; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.Unit; import com.jaamsim.units.UserSpecifiedUnit; public class StringProvListInput extends ListInput<ArrayList<StringProvider>> { private ArrayList<Class<? extends Unit>> unitTypeList; public StringProvListInput(String key, String cat, ArrayList<StringProvider> def) { super(key, cat, def); } public void setUnitTypeList(ArrayList<Class<? extends Unit>> utList) { if (utList.equals(unitTypeList)) return; unitTypeList = new ArrayList<>(utList); this.setValid(false); } public void setUnitType(Class<? extends Unit> u) { ArrayList<Class<? extends Unit>> utList = new ArrayList<>(1); utList.add(u); this.setUnitTypeList(utList); } /** * Returns the unit type for the specified expression. * <p> * If the number of expressions exceeds the number of unit types * then the last unit type in the list is returned. * @param i - index of the expression * @return unit type for the expression */ public Class<? extends Unit> getUnitType(int i) { if (unitTypeList.isEmpty()) return null; int k = Math.min(i, unitTypeList.size()-1); return unitTypeList.get(k); } @Override public int getListSize() { if (value == null) return 0; else return value.size(); } @Override public void copyFrom(Entity thisEnt, Input<?> in) { super.copyFrom(thisEnt, in); // An expression input must be re-parsed to reset the entity referred to by "this" parseFrom(thisEnt, in); } @Override public void parse(Entity thisEnt, KeywordIndex kw) throws InputErrorException { ArrayList<KeywordIndex> subArgs = kw.getSubArgs(); ArrayList<StringProvider> temp = new ArrayList<>(subArgs.size()); for (int i = 0; i < subArgs.size(); i++) { KeywordIndex subArg = subArgs.get(i); try { StringProvider sp = Input.parseStringProvider(subArg, thisEnt, getUnitType(i)); temp.add(sp); } catch (InputErrorException e) { if (subArgs.size() == 1) throw new InputErrorException(e.getMessage()); else throw new InputErrorException(INP_ERR_ELEMENT, i+1, e.getMessage()); } } value = temp; this.setValid(true); } @Override public String getValidInputDesc() { return Input.VALID_STRING_PROV_LIST; } @Override public ArrayList<String> getValidOptions(Entity ent) { ArrayList<String> list = new ArrayList<>(); JaamSimModel simModel = ent.getJaamSimModel(); for (Entity each : simModel.getClonesOfIterator(Entity.class, SampleProvider.class)) { SampleProvider samp = (SampleProvider)each; if (unitTypeList.contains(samp.getUnitType())) list.add(each.getName()); } Collections.sort(list, Input.uiSortOrder); return list; } @Override public void getValueTokens(ArrayList<String> toks) { if (value == null) return; for (int i = 0; i < value.size(); i++) { toks.add("{"); toks.add(value.get(i).toString()); toks.add("}"); } } @Override public String getDefaultString() { if (defValue == null || defValue.isEmpty()) { return ""; } StringBuilder tmp = new StringBuilder(); for (int i = 0; i < defValue.size(); i++) { if (i > 0) tmp.append(SEPARATOR); tmp.append("{ "); tmp.append(defValue.get(i)); tmp.append(" }"); } return tmp.toString(); } @Override public boolean removeReferences(Entity ent) { if (value == null) return false; ArrayList<StringProvider> list = new ArrayList<>(); for (StringProvider samp : value) { if (samp instanceof StringProvSample) { StringProvSample spsamp = (StringProvSample) samp; if (spsamp.getSampleProvider() == ent) { list.add(samp); } } } boolean ret = value.removeAll(list); return ret; } @Override public boolean useExpressionBuilder() { return true; } @Override public String getPresentValueString(double simTime) { if (value == null) return ""; StringBuilder sb = new StringBuilder(); boolean first = true; for (int i = 0; i < value.size(); i++) { StringProvider prov = value.get(i); if (!first) { first = false; } else { sb.append(Input.SEPARATOR); } sb.append("{").append(Input.BRACE_SEPARATOR); Class<? extends Unit> ut = getUnitType(i); if (ut == DimensionlessUnit.class || ut == UserSpecifiedUnit.class) { sb.append(prov.getNextString(simTime)); } else { String unitString = Unit.getDisplayedUnit(ut); double sifactor = Unit.getDisplayedUnitFactor(ut); sb.append(prov.getNextString(simTime, sifactor)); sb.append("[").append(unitString).append("]"); } sb.append(Input.BRACE_SEPARATOR).append("}"); } return sb.toString(); } }
JS: simplify 'getPresentValueString' for StringProvListInput Signed-off-by: Harry King <409587b9e6671aa0763646191d292852dc49a658@gmail.com>
src/main/java/com/jaamsim/StringProviders/StringProvListInput.java
JS: simplify 'getPresentValueString' for StringProvListInput
Java
apache-2.0
a9df683931130ab13efdcda1c00264a07bc4276d
0
RoaringBitmap/RoaringBitmap,okrische/RoaringBitmap,lemire/RoaringBitmap,RoaringBitmap/RoaringBitmap,lemire/RoaringBitmap,lemire/RoaringBitmap,RoaringBitmap/RoaringBitmap,okrische/RoaringBitmap,RoaringBitmap/RoaringBitmap,lemire/RoaringBitmap,okrische/RoaringBitmap
package org.roaringbitmap; /** * Simple extension to the IntIterator interface. * It allows you to "skip" values using the advanceIfNeeded * method, and to look at the value without advancing (peekNext). * * This richer interface enables efficient algorithms over * iterators of integers. */ public interface PeekableIntIterator extends IntIterator { /** * If needed, advance as long as the next value is smaller than minval * * The advanceIfNeeded method is used for performance reasons, to skip * over unnecessary repeated calls to next. * * Suppose for example that you wish to compute the intersection between * an ordered list of integers (e.g., int[] x = {1,4,5}) and a * PeekableIntIterator. * You might do it as follows... * <pre><code> * PeekableIntIterator j = // get an iterator * int val = // first value from my other data structure * j.advanceIfNeeded(val); * while ( j.hasNext() ) { * if(j.next() == val) { * // ah! ah! val is in the intersection... * // do something here * val = // get next value? * } * j.advanceIfNeeded(val); * } * </pre></code> * * The benefit of calling advanceIfNeeded is that each such call * can be much faster than repeated calls to "next". The underlying * implementation can "skip" over some data. * * * @param minval threshold */ public void advanceIfNeeded(int minval); /** * * Look at the next value without advancing * * The peek is useful when working with several iterators at once. * Suppose that you have 100 iterators, and you want to compute * their intersections without materializing the result. * You might do it as follows... * <pre><code> * PriorityQueue pq = new PriorityQueue(100, * new Comparator&lt;PeekableIntIterator&gt;() { * public int compare(PeekableIntIterator a, * PeekableIntIterator b) { * return a.peek() - b.peek(); * } * }); * * //... populate pq * * while(! pq.isEmpty() ) { * // get iterator with a smallest value * PeekableIntIterator pi = pq.poll(); * int x = pi.next(); // advance * // do something with x * if(pi.hasNext()) pq.add(pi) * } * </pre></code> * * Notice how the peek method allows you to compare iterators in a way * that the next method could not do. * * @return next value */ public int peekNext(); /** * Creates a copy of the iterator. * * @return a clone of the current iterator */ @Override PeekableIntIterator clone(); }
src/main/java/org/roaringbitmap/PeekableIntIterator.java
package org.roaringbitmap; /** * Simple extension to the IntIterator interface. * It allows you to "skip" values using the advanceIfNeeded * method, and to look at the value without advancing (peekNext). * */ public interface PeekableIntIterator extends IntIterator { /** * If needed, advance as long as the next value is smaller than minval * * @param minval threshold */ public void advanceIfNeeded(int minval); /** * * Look at the next value without advancing * * @return next value */ public int peekNext(); /** * Creates a copy of the iterator. * * @return a clone of the current iterator */ @Override PeekableIntIterator clone(); }
Justifying PeekableIntInterator
src/main/java/org/roaringbitmap/PeekableIntIterator.java
Justifying PeekableIntInterator
Java
apache-2.0
7964b1aa0d6c681799633f8a20d5ade78aec8289
0
davidzchen/bazel,safarmer/bazel,ButterflyNetwork/bazel,meteorcloudy/bazel,meteorcloudy/bazel,twitter-forks/bazel,safarmer/bazel,bazelbuild/bazel,perezd/bazel,davidzchen/bazel,dropbox/bazel,twitter-forks/bazel,cushon/bazel,bazelbuild/bazel,perezd/bazel,meteorcloudy/bazel,aehlig/bazel,akira-baruah/bazel,dslomov/bazel,dslomov/bazel,akira-baruah/bazel,davidzchen/bazel,dslomov/bazel,perezd/bazel,ulfjack/bazel,dslomov/bazel-windows,aehlig/bazel,perezd/bazel,aehlig/bazel,davidzchen/bazel,werkt/bazel,ulfjack/bazel,werkt/bazel,ulfjack/bazel,aehlig/bazel,twitter-forks/bazel,akira-baruah/bazel,bazelbuild/bazel,perezd/bazel,ulfjack/bazel,dropbox/bazel,safarmer/bazel,ulfjack/bazel,davidzchen/bazel,dropbox/bazel,akira-baruah/bazel,perezd/bazel,ulfjack/bazel,ButterflyNetwork/bazel,dslomov/bazel-windows,bazelbuild/bazel,aehlig/bazel,katre/bazel,dslomov/bazel-windows,dropbox/bazel,katre/bazel,safarmer/bazel,dslomov/bazel,dropbox/bazel,ButterflyNetwork/bazel,safarmer/bazel,cushon/bazel,cushon/bazel,ButterflyNetwork/bazel,meteorcloudy/bazel,werkt/bazel,bazelbuild/bazel,katre/bazel,werkt/bazel,cushon/bazel,ulfjack/bazel,meteorcloudy/bazel,dropbox/bazel,katre/bazel,ButterflyNetwork/bazel,cushon/bazel,dslomov/bazel,aehlig/bazel,werkt/bazel,akira-baruah/bazel,katre/bazel,bazelbuild/bazel,dslomov/bazel-windows,dslomov/bazel,safarmer/bazel,akira-baruah/bazel,aehlig/bazel,twitter-forks/bazel,dslomov/bazel,twitter-forks/bazel,dslomov/bazel-windows,meteorcloudy/bazel,davidzchen/bazel,twitter-forks/bazel,dslomov/bazel-windows,ButterflyNetwork/bazel,werkt/bazel,twitter-forks/bazel,cushon/bazel,meteorcloudy/bazel,katre/bazel,perezd/bazel,davidzchen/bazel
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.android; import static com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition.HOST; import static com.google.devtools.build.lib.packages.Attribute.attr; import static com.google.devtools.build.lib.packages.BuildType.LABEL; import static com.google.devtools.build.lib.packages.BuildType.LABEL_KEYED_STRING_DICT; import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST; import static com.google.devtools.build.lib.packages.BuildType.TRISTATE; import static com.google.devtools.build.lib.packages.ImplicitOutputsFunction.fromTemplates; import static com.google.devtools.build.lib.syntax.Type.BOOLEAN; import static com.google.devtools.build.lib.syntax.Type.INTEGER; import static com.google.devtools.build.lib.syntax.Type.STRING; import static com.google.devtools.build.lib.syntax.Type.STRING_DICT; import static com.google.devtools.build.lib.syntax.Type.STRING_LIST; import static com.google.devtools.build.lib.util.FileTypeSet.ANY_FILE; import static com.google.devtools.build.lib.util.FileTypeSet.NO_FILE; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import com.google.devtools.build.lib.analysis.BaseRuleClasses; import com.google.devtools.build.lib.analysis.RuleDefinition; import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment; import com.google.devtools.build.lib.analysis.config.BuildConfiguration; import com.google.devtools.build.lib.analysis.config.BuildOptions; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.events.EventHandler; import com.google.devtools.build.lib.packages.Attribute; import com.google.devtools.build.lib.packages.Attribute.AllowedValueSet; import com.google.devtools.build.lib.packages.Attribute.LateBoundDefault; import com.google.devtools.build.lib.packages.Attribute.SplitTransition; import com.google.devtools.build.lib.packages.AttributeMap; import com.google.devtools.build.lib.packages.ImplicitOutputsFunction.SafeImplicitOutputsFunction; import com.google.devtools.build.lib.packages.Rule; import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.packages.RuleClass.Builder; import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType; import com.google.devtools.build.lib.packages.RuleTransitionFactory; import com.google.devtools.build.lib.packages.SkylarkProviderIdentifier; import com.google.devtools.build.lib.packages.TriState; import com.google.devtools.build.lib.rules.android.AndroidConfiguration.AndroidAaptVersion; import com.google.devtools.build.lib.rules.android.AndroidConfiguration.AndroidManifestMerger; import com.google.devtools.build.lib.rules.android.AndroidConfiguration.ConfigurationDistinguisher; import com.google.devtools.build.lib.rules.config.ConfigFeatureFlagProvider; import com.google.devtools.build.lib.rules.cpp.CppConfiguration; import com.google.devtools.build.lib.rules.cpp.CppOptions; import com.google.devtools.build.lib.rules.cpp.CppRuleClasses; import com.google.devtools.build.lib.rules.java.JavaConfiguration; import com.google.devtools.build.lib.rules.java.JavaInfo; import com.google.devtools.build.lib.rules.java.JavaSemantics; import com.google.devtools.build.lib.rules.java.ProguardHelper; import com.google.devtools.build.lib.skylarkinterface.SkylarkPrinter; import com.google.devtools.build.lib.skylarkinterface.SkylarkValue; import com.google.devtools.build.lib.syntax.Type; import com.google.devtools.build.lib.util.FileType; import com.google.devtools.build.lib.util.FileTypeSet; import java.util.List; /** Rule definitions for Android rules. */ public final class AndroidRuleClasses { /** Sources generated by a given target, in particular, {@code R.java}. */ public static final SafeImplicitOutputsFunction ANDROID_JAVA_SOURCE_JAR = fromTemplates("%{name}.srcjar"); /** Sources compiled in a given target, excluding {@link #ANDROID_JAVA_SOURCE_JAR}. */ public static final SafeImplicitOutputsFunction ANDROID_LIBRARY_SOURCE_JAR = JavaSemantics.JAVA_LIBRARY_SOURCE_JAR; /** * Compiled sources of a given target, excluding {@link #ANDROID_JAVA_SOURCE_JAR}. This is the * conventional output Jar of any java library target, including android libs. */ public static final SafeImplicitOutputsFunction ANDROID_LIBRARY_CLASS_JAR = JavaSemantics.JAVA_LIBRARY_CLASS_JAR; public static final SafeImplicitOutputsFunction ANDROID_LIBRARY_AAR = fromTemplates("%{name}.aar"); // TODO(b/30307842): Remove this once it is no longer needed for resources migration. public static final SafeImplicitOutputsFunction ANDROID_LIBRARY_APK = fromTemplates("%{name}_files/library.ap_"); /** * Source Jar for {@link #ANDROID_RESOURCES_CLASS_JAR}, which should be the same as {@link * #ANDROID_JAVA_SOURCE_JAR}. */ public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_SOURCE_JAR = fromTemplates("%{name}_resources-src.jar"); /** Compiled {@link #ANDROID_JAVA_SOURCE_JAR}. */ public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_CLASS_JAR = fromTemplates("%{name}_resources.jar"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_APK = fromTemplates("%{name}.ap_"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_AAPT2_LIBRARY_APK = fromTemplates("%{name}_files/aapt2_library.apk"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_AAPT2_R_TXT = fromTemplates("%{name}_symbols/R.aapt2.txt"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_AAPT2_SOURCE_JAR = fromTemplates("%{name}_files/%{name}_resources_aapt2-src.jar"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_SHRUNK_APK = fromTemplates("%{name}_shrunk.ap_"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_ZIP = fromTemplates("%{name}_files/resource_files.zip"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_SHRUNK_ZIP = fromTemplates("%{name}_files/resource_files_shrunk.zip"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCE_SHRINKER_LOG = fromTemplates("%{name}_files/resource_shrinker.log"); public static final SafeImplicitOutputsFunction ANDROID_INCREMENTAL_RESOURCES_APK = fromTemplates("%{name}_files/incremental.ap_"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_APK = fromTemplates("%{name}.apk"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_INCREMENTAL_APK = fromTemplates("%{name}_incremental.apk"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_UNSIGNED_APK = fromTemplates("%{name}_unsigned.apk"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_DEPLOY_JAR = fromTemplates("%{name}_deploy.jar"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_PROGUARD_JAR = fromTemplates("%{name}_proguard.jar"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_INSTRUMENTED_JAR = fromTemplates("%{name}_instrumented.jar"); public static final SafeImplicitOutputsFunction ANDROID_TEST_FILTERED_JAR = fromTemplates("%{name}_filtered.jar"); public static final SafeImplicitOutputsFunction ANDROID_R_TXT = fromTemplates("%{name}_symbols/R.txt"); public static final SafeImplicitOutputsFunction ANDROID_LOCAL_SYMBOLS = fromTemplates("%{name}_symbols/local.bin"); public static final SafeImplicitOutputsFunction ANDROID_MERGED_SYMBOLS = fromTemplates("%{name}_symbols/merged.bin"); public static final SafeImplicitOutputsFunction ANDROID_COMPILED_SYMBOLS = fromTemplates("%{name}_symbols/symbols.zip"); public static final SafeImplicitOutputsFunction ANDROID_SYMLINKED_MANIFEST = fromTemplates("%{name}_symlinked_manifest/AndroidManifest.xml"); public static final SafeImplicitOutputsFunction ANDROID_PROCESSED_MANIFEST = fromTemplates("%{name}_processed_manifest/AndroidManifest.xml"); public static final SafeImplicitOutputsFunction MOBILE_INSTALL_STUB_APPLICATION_MANIFEST = fromTemplates("%{name}_files/mobile_install/AndroidManifest.xml"); public static final SafeImplicitOutputsFunction INSTANT_RUN_STUB_APPLICATION_MANIFEST = fromTemplates("%{name}_files/instant_run/AndroidManifest.xml"); public static final SafeImplicitOutputsFunction FULL_DEPLOY_MARKER = fromTemplates("%{name}_files/full_deploy_marker"); public static final SafeImplicitOutputsFunction INCREMENTAL_DEPLOY_MARKER = fromTemplates("%{name}_files/incremental_deploy_marker"); public static final SafeImplicitOutputsFunction SPLIT_DEPLOY_MARKER = fromTemplates("%{name}_files/split_deploy_marker"); public static final SafeImplicitOutputsFunction MOBILE_INSTALL_ARGS = fromTemplates("%{name}_files/mobile_install_args"); public static final SafeImplicitOutputsFunction DEPLOY_INFO = fromTemplates("%{name}_files/deploy_info.deployinfo.pb"); public static final SafeImplicitOutputsFunction DEPLOY_INFO_INCREMENTAL = fromTemplates("%{name}_files/deploy_info_incremental.deployinfo.pb"); public static final SafeImplicitOutputsFunction DEPLOY_INFO_SPLIT = fromTemplates("%{name}_files/deploy_info_split.deployinfo.pb"); public static final SafeImplicitOutputsFunction REX_OUTPUT_PACKAGE_MAP = fromTemplates("%{name}_rex/rex_output_package.map"); // This needs to be in its own directory because ApkBuilder only has a function (-rf) for source // folders but not source files, and it's easiest to guarantee that nothing gets put beside this // file in the ApkBuilder invocation in this manner public static final SafeImplicitOutputsFunction MOBILE_INSTALL_STUB_APPLICATION_DATA = fromTemplates("%{name}_files/stub_application_data/stub_application_data.txt"); public static final SafeImplicitOutputsFunction DEX_MANIFEST = fromTemplates("%{name}_files/dexmanifest.txt"); public static final SafeImplicitOutputsFunction JAVA_RESOURCES_JAR = fromTemplates("%{name}_files/java_resources.jar"); public static final String MANIFEST_MERGE_TOOL_LABEL = "//tools/android:merge_manifests"; public static final String BUILD_INCREMENTAL_DEXMANIFEST_LABEL = "//tools/android:build_incremental_dexmanifest"; public static final String STUBIFY_MANIFEST_LABEL = "//tools/android:stubify_manifest"; public static final String INCREMENTAL_INSTALL_LABEL = "//tools/android:incremental_install"; public static final String BUILD_SPLIT_MANIFEST_LABEL = "//tools/android:build_split_manifest"; public static final String STRIP_RESOURCES_LABEL = "//tools/android:strip_resources"; public static final String DEFAULT_INCREMENTAL_STUB_APPLICATION = "//tools/android:incremental_stub_application"; public static final String DEFAULT_INCREMENTAL_SPLIT_STUB_APPLICATION = "//tools/android:incremental_split_stub_application"; public static final String DEFAULT_RESOURCES_BUSYBOX = "//tools/android:busybox"; public static final String DEFAULT_SDK = "//tools/android:sdk"; public static final SafeImplicitOutputsFunction ANDROID_DEVICE_USERDATA_IMAGES = fromTemplates("%{name}_images/userdata_images.dat"); public static final SafeImplicitOutputsFunction ANDROID_DEVICE_EMULATOR_METADATA = fromTemplates("%{name}_images/emulator-meta-data.pb"); static final FileType APK = FileType.of(".apk"); public static final String NOCOMPRESS_EXTENSIONS_ATTR = "nocompress_extensions"; /** The default label of android_sdk option */ public static LateBoundDefault<?, Label> getAndroidSdkLabel(Label androidSdk) { return LateBoundDefault.fromTargetConfiguration( AndroidConfiguration.class, androidSdk, (rule, attributes, configuration) -> configuration.getSdk()); } public static final SplitTransition<BuildOptions> ANDROID_SPLIT_TRANSITION = new AndroidSplitTransition(); private static final class AndroidSplitTransition implements SplitTransition<BuildOptions>, SkylarkValue { private static void setCrosstoolToAndroid(BuildOptions output, BuildOptions input) { AndroidConfiguration.Options inputAndroidOptions = input.get(AndroidConfiguration.Options.class); AndroidConfiguration.Options outputAndroidOptions = output.get(AndroidConfiguration.Options.class); CppOptions cppOptions = output.get(CppOptions.class); if (inputAndroidOptions.androidCrosstoolTop != null && !cppOptions.crosstoolTop.equals(inputAndroidOptions.androidCrosstoolTop)) { if (cppOptions.hostCrosstoolTop == null) { cppOptions.hostCrosstoolTop = cppOptions.crosstoolTop; } cppOptions.crosstoolTop = inputAndroidOptions.androidCrosstoolTop; } outputAndroidOptions.configurationDistinguisher = ConfigurationDistinguisher.ANDROID; } @Override public List<BuildOptions> split(BuildOptions buildOptions) { AndroidConfiguration.Options androidOptions = buildOptions.get(AndroidConfiguration.Options.class); CppOptions cppOptions = buildOptions.get(CppOptions.class); Label androidCrosstoolTop = androidOptions.androidCrosstoolTop; if (androidOptions.fatApkCpus.isEmpty()) { if (androidOptions.cpu.isEmpty() || androidCrosstoolTop == null || androidCrosstoolTop.equals(cppOptions.crosstoolTop)) { return ImmutableList.of(); } else { BuildOptions splitOptions = buildOptions.clone(); splitOptions.get(CppOptions.class).cppCompiler = androidOptions.cppCompiler; splitOptions.get(CppOptions.class).libcTopLabel = androidOptions.androidLibcTopLabel; splitOptions.get(BuildConfiguration.Options.class).cpu = androidOptions.cpu; splitOptions.get(CppOptions.class).dynamicMode = androidOptions.dynamicMode; splitOptions.get(CppOptions.class).glibc = null; setCrosstoolToAndroid(splitOptions, buildOptions); return ImmutableList.of(splitOptions); } } else { ImmutableList.Builder<BuildOptions> result = ImmutableList.builder(); for (String cpu : ImmutableSortedSet.copyOf(androidOptions.fatApkCpus)) { BuildOptions splitOptions = buildOptions.clone(); // Disable fat APKs for the child configurations. splitOptions.get(AndroidConfiguration.Options.class).fatApkCpus = ImmutableList.of(); // Set the cpu & android_cpu. // TODO(bazel-team): --android_cpu doesn't follow --cpu right now; it should. splitOptions.get(AndroidConfiguration.Options.class).cpu = cpu; splitOptions.get(BuildConfiguration.Options.class).cpu = cpu; splitOptions.get(CppOptions.class).cppCompiler = androidOptions.cppCompiler; splitOptions.get(CppOptions.class).libcTopLabel = androidOptions.androidLibcTopLabel; splitOptions.get(CppOptions.class).dynamicMode = androidOptions.dynamicMode; splitOptions.get(CppOptions.class).glibc = null; setCrosstoolToAndroid(splitOptions, buildOptions); result.add(splitOptions); } return result.build(); } } @Override public boolean isImmutable() { return true; } @Override public void repr(SkylarkPrinter printer) { printer.append("android_common.multi_cpu_configuration"); } } /** * Turns off dynamic resource filtering for non-Android targets. This prevents unnecessary build * graph bloat. For example, there's no point analyzing distinct cc_library targets for different * resource filter configurations because cc_library semantics doesn't care about filters. */ public static final RuleTransitionFactory REMOVE_DYNAMIC_RESOURCE_FILTERING = new RuleTransitionFactory() { /** Dependencies of these rule class types need to keep resource filtering info. */ private final ImmutableSet<String> keepFilterRuleClasses = ImmutableSet.of("android_binary", "android_library"); @Override public Attribute.Transition buildTransitionFor(Rule depRule) { return keepFilterRuleClasses.contains(depRule.getRuleClass()) ? null : ResourceFilterFactory.REMOVE_DYNAMICALLY_CONFIGURED_RESOURCE_FILTERING_TRANSITION; } }; public static final FileType ANDROID_IDL = FileType.of(".aidl"); public static final String[] ALLOWED_DEPENDENCIES = { "aar_import", "android_library", "cc_library", "java_import", "java_library", "java_lite_proto_library", }; public static boolean hasProguardSpecs(AttributeMap rule) { // The below is a hack to support configurable attributes (proguard_specs seems like // too valuable an attribute to make nonconfigurable, and we don't currently // have the ability to know the configuration when determining implicit outputs). So if the // attribute is configurable, we create the proguard implicit output. At analysis time, we know // the actual value of proguard_specs, and if it is empty we do not use the proguarded jar for // dexing. If the user explicitly tries to build the proguard jar, it will fail. // // TODO(bazel-team): find a stronger approach for this. One simple approach is to somehow // receive 'rule' as an AggregatingAttributeMapper instead of a RawAttributeMapper, // check that all possible values are non-empty, and simply don't support configurable // instances that mix empty and non-empty lists. A more ambitious approach would be // to somehow determine implicit outputs after the configuration is known. A third // approach is to refactor the Android rule logic to avoid these dependencies in the // first place. return rule.isConfigurable("proguard_specs") || !rule.get("proguard_specs", LABEL_LIST).isEmpty(); } public static final SafeImplicitOutputsFunction ANDROID_BINARY_IMPLICIT_OUTPUTS = new SafeImplicitOutputsFunction() { @Override public Iterable<String> getImplicitOutputs(EventHandler eventHandler, AttributeMap rule) { List<SafeImplicitOutputsFunction> functions = Lists.newArrayList(); functions.add(AndroidRuleClasses.ANDROID_BINARY_APK); functions.add(AndroidRuleClasses.ANDROID_BINARY_UNSIGNED_APK); functions.add(AndroidRuleClasses.ANDROID_BINARY_DEPLOY_JAR); if (hasProguardSpecs(rule)) { functions.add(AndroidRuleClasses.ANDROID_BINARY_PROGUARD_JAR); functions.add(JavaSemantics.JAVA_BINARY_PROGUARD_CONFIG); if (ProguardHelper.genProguardMapping(rule)) { functions.add(JavaSemantics.JAVA_BINARY_PROGUARD_MAP); } } return fromFunctions(functions).getImplicitOutputs(eventHandler, rule); } }; public static final SafeImplicitOutputsFunction ANDROID_LIBRARY_IMPLICIT_OUTPUTS = new SafeImplicitOutputsFunction() { @Override public Iterable<String> getImplicitOutputs( EventHandler eventHandler, AttributeMap attributes) { ImmutableList.Builder<SafeImplicitOutputsFunction> implicitOutputs = ImmutableList.builder(); implicitOutputs.add( AndroidRuleClasses.ANDROID_LIBRARY_CLASS_JAR, AndroidRuleClasses.ANDROID_LIBRARY_SOURCE_JAR, AndroidRuleClasses.ANDROID_LIBRARY_AAR); if (LocalResourceContainer.definesAndroidResources(attributes)) { implicitOutputs.add( AndroidRuleClasses.ANDROID_JAVA_SOURCE_JAR, AndroidRuleClasses.ANDROID_R_TXT, AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR); } return fromFunctions(implicitOutputs.build()) .getImplicitOutputs(eventHandler, attributes); } }; /** Definition of the {@code android_sdk} rule. */ public static final class AndroidSdkRule implements RuleDefinition { @Override public RuleClass build(Builder builder, RuleDefinitionEnvironment environment) { return builder .requiresConfigurationFragments(JavaConfiguration.class, AndroidConfiguration.class) .setUndocumented() // build_tools_version is assumed to be the latest version if omitted. .add(attr("build_tools_version", STRING)) // This is the Proguard that comes from the --proguard_top attribute. .add(attr(":proguard", LABEL).cfg(HOST).value(JavaSemantics.PROGUARD).exec()) // This is the Proguard in the BUILD file that contains the android_sdk rule. Used when // --proguard_top is not specified. .add(attr("proguard", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("aapt", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("aapt2", LABEL).cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("dx", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add( attr("main_dex_list_creator", LABEL) .mandatory() .cfg(HOST) .allowedFileTypes(ANY_FILE) .exec()) .add(attr("adb", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("framework_aidl", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE)) .add(attr("aidl", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("aidl_lib", LABEL).allowedFileTypes(JavaSemantics.JAR)) .add(attr("android_jar", LABEL).mandatory().cfg(HOST).allowedFileTypes(JavaSemantics.JAR)) // TODO(b/67903726): Make this attribute mandatory after updating all android_sdk rules. .add(attr("source_properties", LABEL).cfg(HOST).allowedFileTypes(ANY_FILE)) .add(attr("shrinked_android_jar", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE)) .add(attr("annotations_jar", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE)) .add(attr("main_dex_classes", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE)) .add(attr("apkbuilder", LABEL).cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("apksigner", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("zipalign", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add( attr(":java_toolchain", LABEL) .useOutputLicenses() .allowedRuleClasses("java_toolchain") .value(JavaSemantics.JAVA_TOOLCHAIN)) .advertiseProvider(AndroidSdkProvider.class) .build(); } @Override public Metadata getMetadata() { return RuleDefinition.Metadata.builder() .name("android_sdk") .ancestors(BaseRuleClasses.BaseRule.class) .factoryClass(AndroidSdk.class) .build(); } } /** Base class for rule definitions that support resource declarations. */ public static final class AndroidResourceSupportRule implements RuleDefinition { @Override public RuleClass build(RuleClass.Builder builder, final RuleDefinitionEnvironment env) { return builder /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(manifest) --> The name of the Android manifest file, normally <code>AndroidManifest.xml</code>. Must be defined if resource_files or assets are defined. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("manifest", LABEL).allowedFileTypes(FileType.of(".xml"))) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(resource_files) --> The list of resources to be packaged. This is typically a <code>glob</code> of all files under the <code>res</code> directory. <br/> Generated files (from genrules) can be referenced by <a href="../build-ref.html#labels">Label</a> here as well. The only restriction is that the generated outputs must be under the same "<code>res</code>" directory as any other resource files that are included. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("resource_files", LABEL_LIST).allowedFileTypes(FileTypeSet.ANY_FILE)) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(assets_dir) --> The string giving the path to the files in <code>assets</code>. The pair <code>assets</code> and <code>assets_dir</code> describe packaged assets and either both attributes should be provided or none of them. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("assets_dir", STRING)) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(assets) --> The list of assets to be packaged. This is typically a <code>glob</code> of all files under the <code>assets</code> directory. You can also reference other rules (any rule that produces files) or exported files in the other packages, as long as all those files are under the <code>assets_dir</code> directory in the corresponding package. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("assets", LABEL_LIST).allowedFileTypes(FileTypeSet.ANY_FILE)) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(inline_constants) --> Let the compiler inline the constants defined in the generated java sources. This attribute must be set to 0 for all <code>android_library</code> rules used directly by an <code>android_binary</code>, and for any <code>android_binary</code> that has an <code>android_library</code> in its transitive closure. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("inline_constants", BOOLEAN) .undocumented("deprecated noop on library") .value(false)) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(custom_package) --> Java package for which java sources will be generated. By default the package is inferred from the directory where the BUILD file containing the rule is. You can specify a different package but this is highly discouraged since it can introduce classpath conflicts with other libraries that will only be detected at runtime. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("custom_package", STRING)) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(enable_data_binding) --> If true, this rule processes <a href="https://developer.android.com/topic/libraries/data-binding/index.html">data binding</a> expressions in layout resources included through the <a href="${link android_binary.resource_files}">resource_files</a> attribute. Without this setting, data binding expressions produce build failures. <p> To build an Android app with data binding, you must also do the following: <ol> <li>Set this attribute for all Android rules that transitively depend on this one. This is because dependers inherit the rule's data binding expressions through resource merging. So they also need to build with data binding to parse those expressions. <li>Add a <code>deps =</code> entry for the data binding runtime library to all targets that set this attribute. The location of this library depends on your depot setup. </ol> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("enable_data_binding", Type.BOOLEAN)) // The javac annotation processor from Android's data binding library that turns // processed XML expressions into Java code. .add( attr(DataBinding.DATABINDING_ANNOTATION_PROCESSOR_ATTR, LABEL) .cfg(HOST) .value(env.getToolsLabel("//tools/android:databinding_annotation_processor"))) // TODO(b/30816740): Remove this once legacy manifest merging is no longer supported. .add( attr("$android_manifest_merge_tool", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(AndroidRuleClasses.MANIFEST_MERGE_TOOL_LABEL))) .build(); } @Override public Metadata getMetadata() { return RuleDefinition.Metadata.builder() .name("$android_resource_support") .type(RuleClassType.ABSTRACT) .ancestors(AndroidRuleClasses.AndroidBaseRule.class) .build(); } } /** Base class for Android rule definitions. */ public static final class AndroidBaseRule implements RuleDefinition { @Override public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) { return builder .add( attr(":android_sdk", LABEL) .allowedRuleClasses("android_sdk", "filegroup") .value(getAndroidSdkLabel(env.getToolsLabel(AndroidRuleClasses.DEFAULT_SDK)))) /* <!-- #BLAZE_RULE($android_base).ATTRIBUTE(plugins) --> Java compiler plugins to run at compile-time. Every <code>java_plugin</code> specified in the plugins attribute will be run whenever this target is built. Resources generated by the plugin will be included in the result jar of the target. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("plugins", LABEL_LIST) .cfg(HOST) .allowedRuleClasses("java_plugin") .legacyAllowAnyFileType()) .add( attr(":java_plugins", LABEL_LIST) .cfg(HOST) .allowedRuleClasses("java_plugin") .silentRuleClassFilter() .value(JavaSemantics.JAVA_PLUGINS)) /* <!-- #BLAZE_RULE($android_base).ATTRIBUTE(javacopts) --> Extra compiler options for this target. Subject to <a href="${link make-variables}">"Make variable"</a> substitution and <a href="${link common-definitions#sh-tokenization}">Bourne shell tokenization</a>. <p> These compiler options are passed to javac after the global compiler options.</p> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("javacopts", STRING_LIST)) .add( attr("$jarjar_bin", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:jarjar_bin"))) .add( attr("$idlclass", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:IdlClass"))) .add( attr("$desugar_java8_extra_bootclasspath", LABEL) .cfg(HOST) .value(env.getToolsLabel("//tools/android:desugar_java8_extra_bootclasspath"))) .add( attr("$android_resources_busybox", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(DEFAULT_RESOURCES_BUSYBOX))) .build(); } @Override public Metadata getMetadata() { return RuleDefinition.Metadata.builder() .name("$android_base") .type(RuleClassType.ABSTRACT) .ancestors(BaseRuleClasses.RuleBase.class) .build(); } } /** Base class for Android rule definitions that produce binaries. */ public static final class AndroidBinaryBaseRule implements RuleDefinition { private final AndroidNeverlinkAspect androidNeverlinkAspect; private final DexArchiveAspect dexArchiveAspect; public AndroidBinaryBaseRule( AndroidNeverlinkAspect androidNeverlinkAspect, DexArchiveAspect dexArchiveAspect) { this.androidNeverlinkAspect = androidNeverlinkAspect; this.dexArchiveAspect = dexArchiveAspect; } @Override public RuleClass build(RuleClass.Builder builder, final RuleDefinitionEnvironment env) { return builder .requiresConfigurationFragments( AndroidConfiguration.class, JavaConfiguration.class, CppConfiguration.class) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(srcs) --> The list of source files that are processed to create the target. <p><code>srcs</code> files of type <code>.java</code> are compiled. <em>For readability's sake</em>, it is not good to put the name of a generated <code>.java</code> source file into the <code>srcs</code>. Instead, put the depended-on rule name in the <code>srcs</code>, as described below. </p> <p><code>srcs</code> files of type <code>.srcjar</code> are unpacked and compiled. (This is useful if you need to generate a set of .java files with a genrule or build extension.) </p> <p>This rule currently forces source and class compatibility with Java 6. </p> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("srcs", LABEL_LIST) .direct_compile_time_input() .allowedFileTypes(JavaSemantics.JAVA_SOURCE, JavaSemantics.SOURCE_JAR)) // manifest is required for android_binary to ensure that we have an Android package. .override(builder.copy("manifest").mandatory()) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(deps) --> The list of other libraries to be linked in to the binary target. Permitted library types are: <code>android_library</code>, <code>java_library</code> with <code>android</code> constraint and <code>cc_library</code> wrapping or producing <code>.so</code> native libraries for the Android target platform. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .override( builder .copy("deps") .cfg(ANDROID_SPLIT_TRANSITION) .allowedRuleClasses(ALLOWED_DEPENDENCIES) .allowedFileTypes() .aspect(androidNeverlinkAspect) .aspect(dexArchiveAspect, DexArchiveAspect.PARAM_EXTRACTOR)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(debug_key) --> File containing the debug keystore to be used to sign the debug apk. Usually you do not want to use a key other than the default key, so this attribute should be omitted. <p><em class="harmful">WARNING: Do not use your production keys, they should be strictly safeguarded and not kept in your source tree</em>.</p> <p>This keystore must contain a single key named "AndroidDebugKey", and have a keystore password of "android". <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("debug_key", LABEL) .cfg(HOST) .legacyAllowAnyFileType() .value(env.getToolsLabel("//tools/android:debug_keystore"))) .add( attr("feature_of", LABEL) .allowedRuleClasses("android_binary") .allowedFileTypes() .undocumented("experimental, see b/36226333")) .add( attr("feature_after", LABEL) .allowedRuleClasses("android_binary") .allowedFileTypes() .undocumented("experimental, see b/36226333")) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(nocompress_extensions) --> A list of file extension to leave uncompressed in apk. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("nocompress_extensions", STRING_LIST)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(crunch_png) --> Do PNG crunching (or not). This is independent of nine-patch processing, which is always done. Currently only supported for local resources (not android_resources). <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("crunch_png", BOOLEAN).value(true)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(resource_configuration_filters) --> A list of resource configuration filters, such 'en' that will limit the resources in the apk to only the ones in the 'en' configuration. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr(ResourceFilterFactory.RESOURCE_CONFIGURATION_FILTERS_NAME, STRING_LIST)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(shrink_resources) --> Whether to perform resource shrinking. Resources that are not used by the binary will be removed from the APK. This is only supported for rules using local resources (i.e. the <code>manifest</code> and <code>resource_files</code> attributes) and requires ProGuard. It operates in mostly the same manner as the Gradle resource shrinker (https://developer.android.com/studio/build/shrink-code.html#shrink-resources). <p>Notable differences: <ul> <li>resources in <code>values/</code> will be removed as well as file based resources</li> <li>uses <code>strict mode</code> by default</li> <li>removing unused ID resources is not supported</li> </ul> If resource shrinking is enabled, <code><var>name</var>_files/resource_shrinker.log</code> will also be generated, detailing the analysis and deletions performed. <p>Possible values: <ul> <li><code>shrink_resources = 1</code>: Turns on Android resource shrinking</li> <li><code>shrink_resources = 0</code>: Turns off Android resource shrinking</li> <li><code>shrink_resources = -1</code>: Shrinking is controlled by the <a href="../user-manual.html#flag--android_resource_shrinking"> --android_resource_shrinking</a> flag.</li> </ul> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("shrink_resources", TRISTATE).value(TriState.AUTO)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(densities) --> Densities to filter for when building the apk. This will strip out raster drawable resources that would not be loaded by a device with the specified screen densities, to reduce APK size. A corresponding compatible-screens section will also be added to the manifest if it does not already contain a superset listing. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr(ResourceFilterFactory.DENSITIES_NAME, STRING_LIST)) .add( attr("$build_incremental_dexmanifest", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(BUILD_INCREMENTAL_DEXMANIFEST_LABEL))) .add( attr("$stubify_manifest", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(STUBIFY_MANIFEST_LABEL))) .add( attr("$shuffle_jars", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:shuffle_jars"))) .add( attr("$dexbuilder", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:dexbuilder"))) .add( attr("$dexsharder", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:dexsharder"))) .add( attr("$dexmerger", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:dexmerger"))) .add( attr("$merge_dexzips", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:merge_dexzips"))) .add( attr("$incremental_install", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(INCREMENTAL_INSTALL_LABEL))) .add( attr("$build_split_manifest", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(BUILD_SPLIT_MANIFEST_LABEL))) .add( attr("$strip_resources", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(STRIP_RESOURCES_LABEL))) .add( attr("$incremental_stub_application", LABEL) .value(env.getToolsLabel(DEFAULT_INCREMENTAL_STUB_APPLICATION)) .aspect(dexArchiveAspect, DexArchiveAspect.ONLY_DESUGAR_JAVA8)) .add( attr("$incremental_split_stub_application", LABEL) .value(env.getToolsLabel(DEFAULT_INCREMENTAL_SPLIT_STUB_APPLICATION)) .aspect(dexArchiveAspect, DexArchiveAspect.ONLY_DESUGAR_JAVA8)) .add( attr("$desugar", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:desugar_java8"))) .add( attr("$rex_wrapper", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:rex_wrapper"))) .add(attr("rexopts", STRING_LIST)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(dexopts) --> Additional command-line flags for the dx tool when generating classes.dex. Subject to <a href="${link make-variables}">"Make variable"</a> substitution and <a href="${link common-definitions#sh-tokenization}">Bourne shell tokenization</a>. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("dexopts", STRING_LIST)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(dex_shards) --> Number of shards dexing should be decomposed into. This is makes dexing much faster at the expense of app installation and startup time. The larger the binary, the more shards should be used. 25 is a good value to start experimenting with. <p> Note that each shard will result in at least one dex in the final app. For this reason, setting this to more than 1 is not recommended for release binaries. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("dex_shards", INTEGER).value(1)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(incremental_dexing) --> Force the target to be built with or without incremental dexing, overriding defaults and --incremental_dexing flag. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("incremental_dexing", TRISTATE) // Read by DexArchiveAspect's attribute extractor .nonconfigurable("AspectParameters don't support configurations.")) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(multidex) --> Whether to split code into multiple dex files.<br/> Possible values: <ul> <li><code>native</code>: Split code into multiple dex files when the dex 64K index limit is exceeded. Assumes native platform support for loading multidex classes at runtime. <em class="harmful">This works with only Android L and newer</em>.</li> <li><code>legacy</code>: Split code into multiple dex files when the dex 64K index limit is exceeded. Assumes multidex classes are loaded through application code (i.e. no native platform support).</li> <li><code>manual_main_dex</code>: Split code into multiple dex files when the dex 64K index limit is exceeded. The content of the main dex file needs to be specified by providing a list of classes in a text file using the <a href="${link android_binary.main_dex_list}">main_dex_list</a> attribute.</li> <li><code>off</code>: Compile all code to a single dex file, even if it exceeds the index limit.</li> </ul> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("multidex", STRING) .allowedValues(new AllowedValueSet(MultidexMode.getValidValues())) .value(MultidexMode.OFF.getAttributeValue())) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(main_dex_list_opts) --> Command line options to pass to the main dex list builder. Use this option to affect the classes included in the main dex list. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("main_dex_list_opts", STRING_LIST)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(main_dex_list) --> A text file contains a list of class file names. Classes defined by those class files are put in the primary classes.dex. e.g.:<pre class="code"> android/support/multidex/MultiDex$V19.class android/support/multidex/MultiDex.class android/support/multidex/MultiDexApplication.class com/google/common/base/Objects.class </pre> Must be used with <code>multidex="manual_main_dex"</code>. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("main_dex_list", LABEL).legacyAllowAnyFileType()) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(main_dex_proguard_specs) --> Files to be used as the Proguard specifications to determine classes that must be kept in the main dex. Only allowed if the <code>multidex</code> attribute is set to <code>legacy</code>. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("main_dex_proguard_specs", LABEL_LIST).legacyAllowAnyFileType()) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(proguard_specs) --> Files to be used as Proguard specification. This file will describe the set of specifications to be used by Proguard. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("proguard_specs", LABEL_LIST).legacyAllowAnyFileType()) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(proguard_generate_mapping) --> Whether to generate Proguard mapping file. The mapping file will be generated only if <code>proguard_specs</code> is specified. This file will list the mapping between the original and obfuscated class, method, and field names. <p><em class="harmful">WARNING: If this attribute is used, the Proguard specification should contain neither <code>-dontobfuscate</code> nor <code>-printmapping</code>.</em></p> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("proguard_generate_mapping", BOOLEAN) .value(false) .nonconfigurable("value is referenced in an ImplicitOutputsFunction")) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(proguard_apply_mapping) --> File to be used as a mapping for proguard. A mapping file generated by <code>proguard_generate_mapping</code> to be re-used to apply the same mapping to a new build. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("proguard_apply_mapping", LABEL).legacyAllowAnyFileType()) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(proguard_apply_dictionary) --> File to be used as a mapping for proguard. A line separated file of "words" to pull from when renaming classes and members during obfuscation. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("proguard_apply_dictionary", LABEL).legacyAllowAnyFileType()) // TODO(mstaib): Remove this attribute and the matching flag after some cleanup of users .add( attr("legacy_native_support", TRISTATE) .value(TriState.AUTO) .undocumented("No-op, soon to be removed")) .add(attr(":extra_proguard_specs", LABEL_LIST).value(JavaSemantics.EXTRA_PROGUARD_SPECS)) .add( attr(":bytecode_optimizers", LABEL_LIST) .cfg(HOST) .value(JavaSemantics.BYTECODE_OPTIMIZERS)) // We need the C++ toolchain for every sub-configuration to get the correct linker. .add( attr(":cc_toolchain_split", LABEL) .cfg(AndroidRuleClasses.ANDROID_SPLIT_TRANSITION) .value(CppRuleClasses.ccToolchainAttribute(env))) .add(attr("rewrite_dexes_with_rex", BOOLEAN).value(false).undocumented("experimental")) /* File to be used as a package map for Rex tool that keeps the assignment of classes to dex files of a multi-dex application stable over time. Can only be used when <code>proguard_specs</code> is also specified. When <code>proguard_specs</code> is specified, but a package map isn't or there were changes, Rex suggests an updated package map that can be saved and reused for subsequent builds. */ .add(attr("rex_package_map", LABEL).legacyAllowAnyFileType().undocumented("experimental")) /* <!-- #BLAZE_RULE(android_binary).ATTRIBUTE(manifest_merger) --> Select the manifest merger to use for this rule.<br/> Possible values: <ul> <li><code>manifest_merger = "legacy"</code>: Use the legacy manifest merger. Does not allow features of the android merger like placeholder substitution and tools attributes for defining merge behavior. Removes all <code>&lt;uses-permission&gt;</code> and <code>&lt;uses-permission-sdk-23&gt;</code> tags. Performs a tag-level merge.</li> <li><code>manifest_merger = "android"</code>: Use the android manifest merger. Allows features like placeholder substitution and tools attributes for defining merge behavior. Follows the semantics from <a href="http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger"> the documentation</a> except it has been modified to also remove all <code>&lt;uses-permission&gt;</code> and <code>&lt;uses-permission-sdk-23&gt;</code> tags. Performs an attribute-level merge.</li> <li><code>manifest_merger = "auto"</code>: Merger is controlled by the <a href="../user-manual.html#flag--android_manifest_merger"> --android_manifest_merger</a> flag.</li> </ul> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("manifest_merger", STRING) .allowedValues(new AllowedValueSet(AndroidManifestMerger.getAttributeValues())) .value(AndroidManifestMerger.getRuleAttributeDefault())) /* <!-- #BLAZE_RULE(android_binary).ATTRIBUTE(manifest_values) --> A dictionary of values to be overridden in the manifest. Any instance of ${name} in the manifest will be replaced with the value corresponding to name in this dictionary. applicationId, versionCode, versionName, minSdkVersion, targetSdkVersion and maxSdkVersion will also override the corresponding attributes of the manifest and uses-sdk tags. packageName will be ignored and will be set from either applicationId if specified or the package in manifest. When manifest_merger is set to legacy, only applicationId, versionCode and versionName will have any effect. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("manifest_values", STRING_DICT)) /* <!-- #BLAZE_RULE(android_binary).ATTRIBUTE(aapt_version) --> Select the version of aapt for this rule.<br/> Possible values: <ul> <li><code>aapt_version = "aapt"</code>: Use aapt. This is the current default behaviour, and should be used for production binaries. The android_sdk rule must have an aapt binary to use this option.</li> <li><code>aapt_version = "aapt2"</code>: Use aapt2. This is the new resource packaging system that provides improved incremental resource processing, smaller apks and more. The android_sdk rule must have the aapt2 binary to use this option.</li> <li><code>aapt_version = "auto"</code>: aapt is controlled by the --android_aapt_version flag.</li> </ul> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("aapt_version", STRING) .undocumented("experimental, b/28819519") .allowedValues(new AllowedValueSet(AndroidAaptVersion.getAttributeValues())) .value(AndroidAaptVersion.getRuleAttributeDefault())) .add( attr(AndroidFeatureFlagSetProvider.FEATURE_FLAG_ATTR, LABEL_KEYED_STRING_DICT) .undocumented("the feature flag feature has not yet been launched") .allowedRuleClasses("config_feature_flag") .allowedFileTypes() .nonconfigurable("defines an aspect of configuration") .mandatoryProviders(ImmutableList.of(ConfigFeatureFlagProvider.id()))) .add(AndroidFeatureFlagSetProvider.getWhitelistAttribute(env)) // The resource extractor is used at the binary level to extract java resources from the // deploy jar so that they can be added to the APK. .add( attr("$resource_extractor", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:resource_extractor"))) .add( attr("instruments", LABEL) .undocumented("blocked by android_instrumentation_test") .allowedRuleClasses("android_binary") .allowedFileTypes(NO_FILE)) .add( attr("$zip_filter", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:zip_filter"))) .removeAttribute("data") .advertiseProvider(ApkProvider.class) .advertiseSkylarkProvider(SkylarkProviderIdentifier.forKey(JavaInfo.PROVIDER.getKey())) .build(); } @Override public Metadata getMetadata() { return RuleDefinition.Metadata.builder() .name("$android_binary_base") .type(RuleClassType.ABSTRACT) .ancestors(AndroidResourceSupportRule.class) .build(); } } /** Semantic options for the dexer's multidex behavior. */ public enum MultidexMode { // Build dexes with multidex, assuming native platform support for multidex. NATIVE, // Build dexes with multidex and implement support at the application level. LEGACY, // Build dexes with multidex, main dex list needs to be manually specified. MANUAL_MAIN_DEX, // Build all dex code into a single classes.dex file. OFF; /** Returns the attribute value that specifies this mode. */ public String getAttributeValue() { return toString().toLowerCase(); } /** * Returns the name of the output dex classes file. In multidex mode, this is an archive of * (possibly) multiple files. */ public String getOutputDexFilename() { return this == OFF ? "classes.dex" : "classes.dex.zip"; } /** Converts an attribute value to a corresponding mode. Returns null on no match. */ public static MultidexMode fromValue(String value) { for (MultidexMode mode : values()) { if (mode.getAttributeValue().equals(value)) { return mode; } } return null; } /** Enumerates valid values for the "multidex" attribute. */ public static List<String> getValidValues() { List<String> ans = Lists.newArrayList(); for (MultidexMode mode : MultidexMode.values()) { ans.add(mode.getAttributeValue()); } return ans; } } /** Definition of the {@code android_tools_defaults_jar} rule. */ public static final class AndroidToolsDefaultsJarRule implements RuleDefinition { private final Label[] compatibleWithAndroidEnvironments; public AndroidToolsDefaultsJarRule(Label... compatibleWithAndroidEnvironments) { this.compatibleWithAndroidEnvironments = compatibleWithAndroidEnvironments; } @Override public RuleClass build(Builder builder, RuleDefinitionEnvironment environment) { builder .setUndocumented() .add( attr(":android_sdk", LABEL) .allowedRuleClasses("android_sdk", "filegroup") .value(getAndroidSdkLabel(environment.getToolsLabel(DEFAULT_SDK)))); if (compatibleWithAndroidEnvironments.length > 0) { builder.compatibleWith(compatibleWithAndroidEnvironments); } return builder.build(); } @Override public Metadata getMetadata() { return Metadata.builder() .name("android_tools_defaults_jar") .ancestors(BaseRuleClasses.BaseRule.class) .factoryClass(AndroidToolsDefaultsJar.class) .build(); } } }
src/main/java/com/google/devtools/build/lib/rules/android/AndroidRuleClasses.java
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.android; import static com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition.HOST; import static com.google.devtools.build.lib.packages.Attribute.attr; import static com.google.devtools.build.lib.packages.BuildType.LABEL; import static com.google.devtools.build.lib.packages.BuildType.LABEL_KEYED_STRING_DICT; import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST; import static com.google.devtools.build.lib.packages.BuildType.TRISTATE; import static com.google.devtools.build.lib.packages.ImplicitOutputsFunction.fromTemplates; import static com.google.devtools.build.lib.syntax.Type.BOOLEAN; import static com.google.devtools.build.lib.syntax.Type.INTEGER; import static com.google.devtools.build.lib.syntax.Type.STRING; import static com.google.devtools.build.lib.syntax.Type.STRING_DICT; import static com.google.devtools.build.lib.syntax.Type.STRING_LIST; import static com.google.devtools.build.lib.util.FileTypeSet.ANY_FILE; import static com.google.devtools.build.lib.util.FileTypeSet.NO_FILE; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import com.google.devtools.build.lib.analysis.BaseRuleClasses; import com.google.devtools.build.lib.analysis.RuleDefinition; import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment; import com.google.devtools.build.lib.analysis.config.BuildConfiguration; import com.google.devtools.build.lib.analysis.config.BuildOptions; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.events.EventHandler; import com.google.devtools.build.lib.packages.Attribute; import com.google.devtools.build.lib.packages.Attribute.AllowedValueSet; import com.google.devtools.build.lib.packages.Attribute.LateBoundDefault; import com.google.devtools.build.lib.packages.Attribute.SplitTransition; import com.google.devtools.build.lib.packages.AttributeMap; import com.google.devtools.build.lib.packages.ImplicitOutputsFunction.SafeImplicitOutputsFunction; import com.google.devtools.build.lib.packages.Rule; import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.packages.RuleClass.Builder; import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType; import com.google.devtools.build.lib.packages.RuleTransitionFactory; import com.google.devtools.build.lib.packages.SkylarkProviderIdentifier; import com.google.devtools.build.lib.packages.TriState; import com.google.devtools.build.lib.rules.android.AndroidConfiguration.AndroidAaptVersion; import com.google.devtools.build.lib.rules.android.AndroidConfiguration.AndroidManifestMerger; import com.google.devtools.build.lib.rules.android.AndroidConfiguration.ConfigurationDistinguisher; import com.google.devtools.build.lib.rules.config.ConfigFeatureFlagProvider; import com.google.devtools.build.lib.rules.cpp.CppConfiguration; import com.google.devtools.build.lib.rules.cpp.CppOptions; import com.google.devtools.build.lib.rules.cpp.CppRuleClasses; import com.google.devtools.build.lib.rules.java.JavaConfiguration; import com.google.devtools.build.lib.rules.java.JavaInfo; import com.google.devtools.build.lib.rules.java.JavaSemantics; import com.google.devtools.build.lib.rules.java.ProguardHelper; import com.google.devtools.build.lib.skylarkinterface.SkylarkPrinter; import com.google.devtools.build.lib.skylarkinterface.SkylarkValue; import com.google.devtools.build.lib.syntax.Type; import com.google.devtools.build.lib.util.FileType; import com.google.devtools.build.lib.util.FileTypeSet; import java.util.List; /** Rule definitions for Android rules. */ public final class AndroidRuleClasses { /** Sources generated by a given target, in particular, {@code R.java}. */ public static final SafeImplicitOutputsFunction ANDROID_JAVA_SOURCE_JAR = fromTemplates("%{name}.srcjar"); /** Sources compiled in a given target, excluding {@link #ANDROID_JAVA_SOURCE_JAR}. */ public static final SafeImplicitOutputsFunction ANDROID_LIBRARY_SOURCE_JAR = JavaSemantics.JAVA_LIBRARY_SOURCE_JAR; /** * Compiled sources of a given target, excluding {@link #ANDROID_JAVA_SOURCE_JAR}. This is the * conventional output Jar of any java library target, including android libs. */ public static final SafeImplicitOutputsFunction ANDROID_LIBRARY_CLASS_JAR = JavaSemantics.JAVA_LIBRARY_CLASS_JAR; public static final SafeImplicitOutputsFunction ANDROID_LIBRARY_AAR = fromTemplates("%{name}.aar"); // TODO(b/30307842): Remove this once it is no longer needed for resources migration. public static final SafeImplicitOutputsFunction ANDROID_LIBRARY_APK = fromTemplates("%{name}_files/library.ap_"); /** * Source Jar for {@link #ANDROID_RESOURCES_CLASS_JAR}, which should be the same as {@link * #ANDROID_JAVA_SOURCE_JAR}. */ public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_SOURCE_JAR = fromTemplates("%{name}_resources-src.jar"); /** Compiled {@link #ANDROID_JAVA_SOURCE_JAR}. */ public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_CLASS_JAR = fromTemplates("%{name}_resources.jar"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_APK = fromTemplates("%{name}.ap_"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_AAPT2_LIBRARY_APK = fromTemplates("%{name}_files/aapt2_library.apk"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_AAPT2_R_TXT = fromTemplates("%{name}_symbols/R.aapt2.txt"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_AAPT2_SOURCE_JAR = fromTemplates("%{name}_files/%{name}_resources_aapt2-src.jar"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_SHRUNK_APK = fromTemplates("%{name}_shrunk.ap_"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_ZIP = fromTemplates("%{name}_files/resource_files.zip"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCES_SHRUNK_ZIP = fromTemplates("%{name}_files/resource_files_shrunk.zip"); public static final SafeImplicitOutputsFunction ANDROID_RESOURCE_SHRINKER_LOG = fromTemplates("%{name}_files/resource_shrinker.log"); public static final SafeImplicitOutputsFunction ANDROID_INCREMENTAL_RESOURCES_APK = fromTemplates("%{name}_files/incremental.ap_"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_APK = fromTemplates("%{name}.apk"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_INCREMENTAL_APK = fromTemplates("%{name}_incremental.apk"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_UNSIGNED_APK = fromTemplates("%{name}_unsigned.apk"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_DEPLOY_JAR = fromTemplates("%{name}_deploy.jar"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_PROGUARD_JAR = fromTemplates("%{name}_proguard.jar"); public static final SafeImplicitOutputsFunction ANDROID_BINARY_INSTRUMENTED_JAR = fromTemplates("%{name}_instrumented.jar"); public static final SafeImplicitOutputsFunction ANDROID_TEST_FILTERED_JAR = fromTemplates("%{name}_filtered.jar"); public static final SafeImplicitOutputsFunction ANDROID_R_TXT = fromTemplates("%{name}_symbols/R.txt"); public static final SafeImplicitOutputsFunction ANDROID_LOCAL_SYMBOLS = fromTemplates("%{name}_symbols/local.bin"); public static final SafeImplicitOutputsFunction ANDROID_MERGED_SYMBOLS = fromTemplates("%{name}_symbols/merged.bin"); public static final SafeImplicitOutputsFunction ANDROID_COMPILED_SYMBOLS = fromTemplates("%{name}_symbols/symbols.zip"); public static final SafeImplicitOutputsFunction ANDROID_SYMLINKED_MANIFEST = fromTemplates("%{name}_symlinked_manifest/AndroidManifest.xml"); public static final SafeImplicitOutputsFunction ANDROID_PROCESSED_MANIFEST = fromTemplates("%{name}_processed_manifest/AndroidManifest.xml"); public static final SafeImplicitOutputsFunction MOBILE_INSTALL_STUB_APPLICATION_MANIFEST = fromTemplates("%{name}_files/mobile_install/AndroidManifest.xml"); public static final SafeImplicitOutputsFunction INSTANT_RUN_STUB_APPLICATION_MANIFEST = fromTemplates("%{name}_files/instant_run/AndroidManifest.xml"); public static final SafeImplicitOutputsFunction FULL_DEPLOY_MARKER = fromTemplates("%{name}_files/full_deploy_marker"); public static final SafeImplicitOutputsFunction INCREMENTAL_DEPLOY_MARKER = fromTemplates("%{name}_files/incremental_deploy_marker"); public static final SafeImplicitOutputsFunction SPLIT_DEPLOY_MARKER = fromTemplates("%{name}_files/split_deploy_marker"); public static final SafeImplicitOutputsFunction MOBILE_INSTALL_ARGS = fromTemplates("%{name}_files/mobile_install_args"); public static final SafeImplicitOutputsFunction DEPLOY_INFO = fromTemplates("%{name}_files/deploy_info.deployinfo.pb"); public static final SafeImplicitOutputsFunction DEPLOY_INFO_INCREMENTAL = fromTemplates("%{name}_files/deploy_info_incremental.deployinfo.pb"); public static final SafeImplicitOutputsFunction DEPLOY_INFO_SPLIT = fromTemplates("%{name}_files/deploy_info_split.deployinfo.pb"); public static final SafeImplicitOutputsFunction REX_OUTPUT_PACKAGE_MAP = fromTemplates("%{name}_rex/rex_output_package.map"); // This needs to be in its own directory because ApkBuilder only has a function (-rf) for source // folders but not source files, and it's easiest to guarantee that nothing gets put beside this // file in the ApkBuilder invocation in this manner public static final SafeImplicitOutputsFunction MOBILE_INSTALL_STUB_APPLICATION_DATA = fromTemplates("%{name}_files/stub_application_data/stub_application_data.txt"); public static final SafeImplicitOutputsFunction DEX_MANIFEST = fromTemplates("%{name}_files/dexmanifest.txt"); public static final SafeImplicitOutputsFunction JAVA_RESOURCES_JAR = fromTemplates("%{name}_files/java_resources.jar"); public static final String MANIFEST_MERGE_TOOL_LABEL = "//tools/android:merge_manifests"; public static final String BUILD_INCREMENTAL_DEXMANIFEST_LABEL = "//tools/android:build_incremental_dexmanifest"; public static final String STUBIFY_MANIFEST_LABEL = "//tools/android:stubify_manifest"; public static final String INCREMENTAL_INSTALL_LABEL = "//tools/android:incremental_install"; public static final String BUILD_SPLIT_MANIFEST_LABEL = "//tools/android:build_split_manifest"; public static final String STRIP_RESOURCES_LABEL = "//tools/android:strip_resources"; public static final String DEFAULT_INCREMENTAL_STUB_APPLICATION = "//tools/android:incremental_stub_application"; public static final String DEFAULT_INCREMENTAL_SPLIT_STUB_APPLICATION = "//tools/android:incremental_split_stub_application"; public static final String DEFAULT_RESOURCES_BUSYBOX = "//tools/android:busybox"; public static final String DEFAULT_SDK = "//tools/android:sdk"; public static final SafeImplicitOutputsFunction ANDROID_DEVICE_USERDATA_IMAGES = fromTemplates("%{name}_images/userdata_images.dat"); public static final SafeImplicitOutputsFunction ANDROID_DEVICE_EMULATOR_METADATA = fromTemplates("%{name}_images/emulator-meta-data.pb"); static final FileType APK = FileType.of(".apk"); public static final String NOCOMPRESS_EXTENSIONS_ATTR = "nocompress_extensions"; /** The default label of android_sdk option */ public static LateBoundDefault<?, Label> getAndroidSdkLabel(Label androidSdk) { return LateBoundDefault.fromTargetConfiguration( AndroidConfiguration.class, androidSdk, (rule, attributes, configuration) -> configuration.getSdk()); } public static final SplitTransition<BuildOptions> ANDROID_SPLIT_TRANSITION = new AndroidSplitTransition(); private static final class AndroidSplitTransition implements SplitTransition<BuildOptions>, SkylarkValue { private static void setCrosstoolToAndroid(BuildOptions output, BuildOptions input) { AndroidConfiguration.Options inputAndroidOptions = input.get(AndroidConfiguration.Options.class); AndroidConfiguration.Options outputAndroidOptions = output.get(AndroidConfiguration.Options.class); CppOptions cppOptions = output.get(CppOptions.class); if (inputAndroidOptions.androidCrosstoolTop != null && !cppOptions.crosstoolTop.equals(inputAndroidOptions.androidCrosstoolTop)) { if (cppOptions.hostCrosstoolTop == null) { cppOptions.hostCrosstoolTop = cppOptions.crosstoolTop; } cppOptions.crosstoolTop = inputAndroidOptions.androidCrosstoolTop; } outputAndroidOptions.configurationDistinguisher = ConfigurationDistinguisher.ANDROID; } @Override public List<BuildOptions> split(BuildOptions buildOptions) { AndroidConfiguration.Options androidOptions = buildOptions.get(AndroidConfiguration.Options.class); CppOptions cppOptions = buildOptions.get(CppOptions.class); Label androidCrosstoolTop = androidOptions.androidCrosstoolTop; if (androidOptions.fatApkCpus.isEmpty()) { if (androidOptions.cpu.isEmpty() || androidCrosstoolTop == null || androidCrosstoolTop.equals(cppOptions.crosstoolTop)) { return ImmutableList.of(); } else { BuildOptions splitOptions = buildOptions.clone(); splitOptions.get(CppOptions.class).cppCompiler = androidOptions.cppCompiler; splitOptions.get(CppOptions.class).libcTopLabel = androidOptions.androidLibcTopLabel; splitOptions.get(BuildConfiguration.Options.class).cpu = androidOptions.cpu; splitOptions.get(CppOptions.class).dynamicMode = androidOptions.dynamicMode; splitOptions.get(CppOptions.class).glibc = null; setCrosstoolToAndroid(splitOptions, buildOptions); return ImmutableList.of(splitOptions); } } else { ImmutableList.Builder<BuildOptions> result = ImmutableList.builder(); for (String cpu : ImmutableSortedSet.copyOf(androidOptions.fatApkCpus)) { BuildOptions splitOptions = buildOptions.clone(); // Disable fat APKs for the child configurations. splitOptions.get(AndroidConfiguration.Options.class).fatApkCpus = ImmutableList.of(); // Set the cpu & android_cpu. // TODO(bazel-team): --android_cpu doesn't follow --cpu right now; it should. splitOptions.get(AndroidConfiguration.Options.class).cpu = cpu; splitOptions.get(BuildConfiguration.Options.class).cpu = cpu; splitOptions.get(CppOptions.class).cppCompiler = androidOptions.cppCompiler; splitOptions.get(CppOptions.class).libcTopLabel = androidOptions.androidLibcTopLabel; splitOptions.get(CppOptions.class).dynamicMode = androidOptions.dynamicMode; splitOptions.get(CppOptions.class).glibc = null; setCrosstoolToAndroid(splitOptions, buildOptions); result.add(splitOptions); } return result.build(); } } @Override public boolean isImmutable() { return true; } @Override public void repr(SkylarkPrinter printer) { printer.append("android_common.multi_cpu_configuration"); } } /** * Turns off dynamic resource filtering for non-Android targets. This prevents unnecessary build * graph bloat. For example, there's no point analyzing distinct cc_library targets for different * resource filter configurations because cc_library semantics doesn't care about filters. */ public static final RuleTransitionFactory REMOVE_DYNAMIC_RESOURCE_FILTERING = new RuleTransitionFactory() { /** Dependencies of these rule class types need to keep resource filtering info. */ private final ImmutableSet<String> keepFilterRuleClasses = ImmutableSet.of("android_binary", "android_library"); @Override public Attribute.Transition buildTransitionFor(Rule depRule) { return keepFilterRuleClasses.contains(depRule.getRuleClass()) ? null : ResourceFilterFactory.REMOVE_DYNAMICALLY_CONFIGURED_RESOURCE_FILTERING_TRANSITION; } }; public static final FileType ANDROID_IDL = FileType.of(".aidl"); public static final String[] ALLOWED_DEPENDENCIES = { "aar_import", "android_library", "cc_library", "java_import", "java_library", "java_lite_proto_library", }; public static boolean hasProguardSpecs(AttributeMap rule) { // The below is a hack to support configurable attributes (proguard_specs seems like // too valuable an attribute to make nonconfigurable, and we don't currently // have the ability to know the configuration when determining implicit outputs). So if the // attribute is configurable, we create the proguard implicit output. At analysis time, we know // the actual value of proguard_specs, and if it is empty we do not use the proguarded jar for // dexing. If the user explicitly tries to build the proguard jar, it will fail. // // TODO(bazel-team): find a stronger approach for this. One simple approach is to somehow // receive 'rule' as an AggregatingAttributeMapper instead of a RawAttributeMapper, // check that all possible values are non-empty, and simply don't support configurable // instances that mix empty and non-empty lists. A more ambitious approach would be // to somehow determine implicit outputs after the configuration is known. A third // approach is to refactor the Android rule logic to avoid these dependencies in the // first place. return rule.isConfigurable("proguard_specs") || !rule.get("proguard_specs", LABEL_LIST).isEmpty(); } public static final SafeImplicitOutputsFunction ANDROID_BINARY_IMPLICIT_OUTPUTS = new SafeImplicitOutputsFunction() { @Override public Iterable<String> getImplicitOutputs(EventHandler eventHandler, AttributeMap rule) { List<SafeImplicitOutputsFunction> functions = Lists.newArrayList(); functions.add(AndroidRuleClasses.ANDROID_BINARY_APK); functions.add(AndroidRuleClasses.ANDROID_BINARY_UNSIGNED_APK); functions.add(AndroidRuleClasses.ANDROID_BINARY_DEPLOY_JAR); if (hasProguardSpecs(rule)) { functions.add(AndroidRuleClasses.ANDROID_BINARY_PROGUARD_JAR); functions.add(JavaSemantics.JAVA_BINARY_PROGUARD_CONFIG); if (ProguardHelper.genProguardMapping(rule)) { functions.add(JavaSemantics.JAVA_BINARY_PROGUARD_MAP); } } return fromFunctions(functions).getImplicitOutputs(eventHandler, rule); } }; public static final SafeImplicitOutputsFunction ANDROID_LIBRARY_IMPLICIT_OUTPUTS = new SafeImplicitOutputsFunction() { @Override public Iterable<String> getImplicitOutputs( EventHandler eventHandler, AttributeMap attributes) { ImmutableList.Builder<SafeImplicitOutputsFunction> implicitOutputs = ImmutableList.builder(); implicitOutputs.add( AndroidRuleClasses.ANDROID_LIBRARY_CLASS_JAR, AndroidRuleClasses.ANDROID_LIBRARY_SOURCE_JAR, AndroidRuleClasses.ANDROID_LIBRARY_AAR); if (LocalResourceContainer.definesAndroidResources(attributes)) { implicitOutputs.add( AndroidRuleClasses.ANDROID_JAVA_SOURCE_JAR, AndroidRuleClasses.ANDROID_R_TXT, AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR); } return fromFunctions(implicitOutputs.build()) .getImplicitOutputs(eventHandler, attributes); } }; /** Definition of the {@code android_sdk} rule. */ public static final class AndroidSdkRule implements RuleDefinition { @Override public RuleClass build(Builder builder, RuleDefinitionEnvironment environment) { return builder .requiresConfigurationFragments(JavaConfiguration.class, AndroidConfiguration.class) .setUndocumented() // build_tools_version is assumed to be the latest version if omitted. .add(attr("build_tools_version", STRING)) // This is the Proguard that comes from the --proguard_top attribute. .add(attr(":proguard", LABEL).cfg(HOST).value(JavaSemantics.PROGUARD).exec()) // This is the Proguard in the BUILD file that contains the android_sdk rule. Used when // --proguard_top is not specified. .add(attr("proguard", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("aapt", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("aapt2", LABEL).cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("dx", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add( attr("main_dex_list_creator", LABEL) .mandatory() .cfg(HOST) .allowedFileTypes(ANY_FILE) .exec()) .add(attr("adb", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("framework_aidl", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE)) .add(attr("aidl", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("aidl_lib", LABEL).allowedFileTypes(JavaSemantics.JAR)) .add(attr("android_jar", LABEL).mandatory().cfg(HOST).allowedFileTypes(JavaSemantics.JAR)) // TODO(b/67903726): Make this attribute mandatory after updating all android_sdk rules. .add(attr("source_properties", LABEL).cfg(HOST).allowedFileTypes(ANY_FILE)) .add(attr("shrinked_android_jar", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE)) .add(attr("annotations_jar", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE)) .add(attr("main_dex_classes", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE)) .add(attr("apkbuilder", LABEL).cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("apksigner", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add(attr("zipalign", LABEL).mandatory().cfg(HOST).allowedFileTypes(ANY_FILE).exec()) .add( attr(":java_toolchain", LABEL) .useOutputLicenses() .allowedRuleClasses("java_toolchain") .value(JavaSemantics.JAVA_TOOLCHAIN)) .advertiseProvider(AndroidSdkProvider.class) .build(); } @Override public Metadata getMetadata() { return RuleDefinition.Metadata.builder() .name("android_sdk") .ancestors(BaseRuleClasses.BaseRule.class) .factoryClass(AndroidSdk.class) .build(); } } /** Base class for rule definitions that support resource declarations. */ public static final class AndroidResourceSupportRule implements RuleDefinition { @Override public RuleClass build(RuleClass.Builder builder, final RuleDefinitionEnvironment env) { return builder /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(manifest) --> The name of the Android manifest file, normally <code>AndroidManifest.xml</code>. Must be defined if resource_files or assets are defined. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("manifest", LABEL).allowedFileTypes(FileType.of(".xml"))) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(resource_files) --> The list of resources to be packaged. This is typically a <code>glob</code> of all files under the <code>res</code> directory. <br/> Generated files (from genrules) can be referenced by <a href="../build-ref.html#labels">Label</a> here as well. The only restriction is that the generated outputs must be under the same "<code>res</code>" directory as any other resource files that are included. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("resource_files", LABEL_LIST).allowedFileTypes(FileTypeSet.ANY_FILE)) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(assets_dir) --> The string giving the path to the files in <code>assets</code>. The pair <code>assets</code> and <code>assets_dir</code> describe packaged assets and either both attributes should be provided or none of them. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("assets_dir", STRING)) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(assets) --> The list of assets to be packaged. This is typically a <code>glob</code> of all files under the <code>assets</code> directory. You can also reference other rules (any rule that produces files) or exported files in the other packages, as long as all those files are under the <code>assets_dir</code> directory in the corresponding package. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("assets", LABEL_LIST).allowedFileTypes(FileTypeSet.ANY_FILE)) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(inline_constants) --> Let the compiler inline the constants defined in the generated java sources. This attribute must be set to 0 for all <code>android_library</code> rules used directly by an <code>android_binary</code>, and for any <code>android_binary</code> that has an <code>android_library</code> in its transitive closure. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("inline_constants", BOOLEAN) .undocumented("deprecated noop on library") .value(false)) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(custom_package) --> Java package for which java sources will be generated. By default the package is inferred from the directory where the BUILD file containing the rule is. You can specify a different package but this is highly discouraged since it can introduce classpath conflicts with other libraries that will only be detected at runtime. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("custom_package", STRING)) /* <!-- #BLAZE_RULE($android_resource_support).ATTRIBUTE(enable_data_binding) --> If true, this rule processes <a href="https://developer.android.com/topic/libraries/data-binding/index.html">data binding</a> expressions in layout resources included through the <a href="${link android_binary.resource_files}">resource_files</a> attribute. Without this setting, data binding expressions produce build failures. <p> To build an Android app with data binding, you must also do the following: <ol> <li>Set this attribute for all Android rules that transitively depend on this one. This is because dependers inherit the rule's data binding expressions through resource merging. So they also need to build with data binding to parse those expressions. <li>Add a <code>deps =</code> entry for the data binding runtime library to all targets that set this attribute. The location of this library depends on your depot setup. </ol> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("enable_data_binding", Type.BOOLEAN)) // The javac annotation processor from Android's data binding library that turns // processed XML expressions into Java code. .add( attr(DataBinding.DATABINDING_ANNOTATION_PROCESSOR_ATTR, LABEL) .cfg(HOST) .value(env.getToolsLabel("//tools/android:databinding_annotation_processor"))) // TODO(b/30816740): Remove this once legacy manifest merging is no longer supported. .add( attr("$android_manifest_merge_tool", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(AndroidRuleClasses.MANIFEST_MERGE_TOOL_LABEL))) .build(); } @Override public Metadata getMetadata() { return RuleDefinition.Metadata.builder() .name("$android_resource_support") .type(RuleClassType.ABSTRACT) .ancestors(AndroidRuleClasses.AndroidBaseRule.class) .build(); } } /** Base class for Android rule definitions. */ public static final class AndroidBaseRule implements RuleDefinition { @Override public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment env) { return builder .add( attr(":android_sdk", LABEL) .allowedRuleClasses("android_sdk", "filegroup") .value(getAndroidSdkLabel(env.getToolsLabel(AndroidRuleClasses.DEFAULT_SDK)))) /* <!-- #BLAZE_RULE($android_base).ATTRIBUTE(plugins) --> Java compiler plugins to run at compile-time. Every <code>java_plugin</code> specified in the plugins attribute will be run whenever this target is built. Resources generated by the plugin will be included in the result jar of the target. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("plugins", LABEL_LIST) .cfg(HOST) .allowedRuleClasses("java_plugin") .legacyAllowAnyFileType()) .add( attr(":java_plugins", LABEL_LIST) .cfg(HOST) .allowedRuleClasses("java_plugin") .silentRuleClassFilter() .value(JavaSemantics.JAVA_PLUGINS)) /* <!-- #BLAZE_RULE($android_base).ATTRIBUTE(javacopts) --> Extra compiler options for this target. Subject to <a href="${link make-variables}">"Make variable"</a> substitution and <a href="${link common-definitions#sh-tokenization}">Bourne shell tokenization</a>. <p> These compiler options are passed to javac after the global compiler options.</p> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("javacopts", STRING_LIST)) .add( attr("$jarjar_bin", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:jarjar_bin"))) .add( attr("$idlclass", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:IdlClass"))) .add( attr("$desugar_java8_extra_bootclasspath", LABEL) .cfg(HOST) .value(env.getToolsLabel("//tools/android:desugar_java8_extra_bootclasspath"))) .add( attr("$android_resources_busybox", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(DEFAULT_RESOURCES_BUSYBOX))) .build(); } @Override public Metadata getMetadata() { return RuleDefinition.Metadata.builder() .name("$android_base") .type(RuleClassType.ABSTRACT) .ancestors(BaseRuleClasses.RuleBase.class) .build(); } } /** Base class for Android rule definitions that produce binaries. */ public static final class AndroidBinaryBaseRule implements RuleDefinition { private final AndroidNeverlinkAspect androidNeverlinkAspect; private final DexArchiveAspect dexArchiveAspect; public AndroidBinaryBaseRule( AndroidNeverlinkAspect androidNeverlinkAspect, DexArchiveAspect dexArchiveAspect) { this.androidNeverlinkAspect = androidNeverlinkAspect; this.dexArchiveAspect = dexArchiveAspect; } @Override public RuleClass build(RuleClass.Builder builder, final RuleDefinitionEnvironment env) { return builder .requiresConfigurationFragments( AndroidConfiguration.class, JavaConfiguration.class, CppConfiguration.class) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(srcs) --> The list of source files that are processed to create the target. <p><code>srcs</code> files of type <code>.java</code> are compiled. <em>For readability's sake</em>, it is not good to put the name of a generated <code>.java</code> source file into the <code>srcs</code>. Instead, put the depended-on rule name in the <code>srcs</code>, as described below. </p> <p><code>srcs</code> files of type <code>.srcjar</code> are unpacked and compiled. (This is useful if you need to generate a set of .java files with a genrule or build extension.) </p> <p>This rule currently forces source and class compatibility with Java 6. </p> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("srcs", LABEL_LIST) .direct_compile_time_input() .allowedFileTypes(JavaSemantics.JAVA_SOURCE, JavaSemantics.SOURCE_JAR)) // manifest is required for android_binary to ensure that we have an Android package. .override(builder.copy("manifest").mandatory()) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(deps) --> The list of other libraries to be linked in to the binary target. Permitted library types are: <code>android_library</code>, <code>java_library</code> with <code>android</code> constraint and <code>cc_library</code> wrapping or producing <code>.so</code> native libraries for the Android target platform. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .override( builder .copy("deps") .cfg(ANDROID_SPLIT_TRANSITION) .allowedRuleClasses(ALLOWED_DEPENDENCIES) .allowedFileTypes() .aspect(androidNeverlinkAspect) .aspect(dexArchiveAspect, DexArchiveAspect.PARAM_EXTRACTOR)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(debug_key) --> File containing the debug keystore to be used to sign the debug apk. Usually you do not want to use a key other than the default key, so this attribute should be omitted. <p><em class="harmful">WARNING: Do not use your production keys, they should be strictly safeguarded and not kept in your source tree</em>.</p> <p>This keystore must contain a single key named "AndroidDebugKey", and have a keystore password of "android". <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("debug_key", LABEL) .cfg(HOST) .legacyAllowAnyFileType() .value(env.getToolsLabel("//tools/android:debug_keystore"))) .add( attr("feature_of", LABEL) .allowedRuleClasses("android_binary") .allowedFileTypes() .undocumented("experimental, see b/36226333")) .add( attr("feature_after", LABEL) .allowedRuleClasses("android_binary") .allowedFileTypes() .undocumented("experimental, see b/36226333")) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(nocompress_extensions) --> A list of file extension to leave uncompressed in apk. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("nocompress_extensions", STRING_LIST)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(crunch_png) --> Do PNG crunching (or not). This is independent of nine-patch processing, which is always done. Currently only supported for local resources (not android_resources). <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("crunch_png", BOOLEAN).value(true)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(resource_configuration_filters) --> A list of resource configuration filters, such 'en' that will limit the resources in the apk to only the ones in the 'en' configuration. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr(ResourceFilterFactory.RESOURCE_CONFIGURATION_FILTERS_NAME, STRING_LIST)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(shrink_resources) --> Whether to perform resource shrinking. Resources that are not used by the binary will be removed from the APK. This is only supported for rules using local resources (i.e. the <code>manifest</code> and <code>resource_files</code> attributes) and requires ProGuard. It operates in mostly the same manner as the Gradle resource shrinker (https://developer.android.com/studio/build/shrink-code.html#shrink-resources). <p>Notable differences: <ul> <li>resources in <code>values/</code> will be removed as well as file based resources</li> <li>uses <code>strict mode</code> by default</li> <li>removing unused ID resources is not supported</li> </ul> If resource shrinking is enabled, <code><var>name</var>_files/resource_shrinker.log</code> will also be generated, detailing the analysis and deletions performed. <p>Possible values: <ul> <li><code>shrink_resources = 1</code>: Turns on Android resource shrinking</li> <li><code>shrink_resources = 0</code>: Turns off Android resource shrinking</li> <li><code>shrink_resources = -1</code>: Shrinking is controlled by the <a href="../user-manual.html#flag--android_resource_shrinking"> --android_resource_shrinking</a> flag.</li> </ul> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("shrink_resources", TRISTATE).value(TriState.AUTO)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(densities) --> Densities to filter for when building the apk. This will strip out raster drawable resources that would not be loaded by a device with the specified screen densities, to reduce APK size. A corresponding compatible-screens section will also be added to the manifest if it does not already contain a superset listing. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr(ResourceFilterFactory.DENSITIES_NAME, STRING_LIST)) .add( attr("$build_incremental_dexmanifest", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(BUILD_INCREMENTAL_DEXMANIFEST_LABEL))) .add( attr("$stubify_manifest", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(STUBIFY_MANIFEST_LABEL))) .add( attr("$shuffle_jars", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:shuffle_jars"))) .add( attr("$dexbuilder", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:dexbuilder"))) .add( attr("$dexsharder", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:dexsharder"))) .add( attr("$dexmerger", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:dexmerger"))) .add( attr("$merge_dexzips", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:merge_dexzips"))) .add( attr("$incremental_install", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(INCREMENTAL_INSTALL_LABEL))) .add( attr("$build_split_manifest", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(BUILD_SPLIT_MANIFEST_LABEL))) .add( attr("$strip_resources", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel(STRIP_RESOURCES_LABEL))) .add( attr("$incremental_stub_application", LABEL) .value(env.getToolsLabel(DEFAULT_INCREMENTAL_STUB_APPLICATION)) .aspect(dexArchiveAspect, DexArchiveAspect.ONLY_DESUGAR_JAVA8)) .add( attr("$incremental_split_stub_application", LABEL) .value(env.getToolsLabel(DEFAULT_INCREMENTAL_SPLIT_STUB_APPLICATION)) .aspect(dexArchiveAspect, DexArchiveAspect.ONLY_DESUGAR_JAVA8)) .add( attr("$desugar", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:desugar_java8"))) .add( attr("$rex_wrapper", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:rex_wrapper"))) .add(attr("rexopts", STRING_LIST)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(dexopts) --> Additional command-line flags for the dx tool when generating classes.dex. Subject to <a href="${link make-variables}">"Make variable"</a> substitution and <a href="${link common-definitions#sh-tokenization}">Bourne shell tokenization</a>. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("dexopts", STRING_LIST)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(dex_shards) --> Number of shards dexing should be decomposed into. This is makes dexing much faster at the expense of app installation and startup time. The larger the binary, the more shards should be used. 25 is a good value to start experimenting with. <p> Note that each shard will result in at least one dex in the final app. For this reason, setting this to more than 1 is not recommended for release binaries. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("dex_shards", INTEGER).value(1)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(incremental_dexing) --> Force the target to be built with or without incremental dexing, overriding defaults and --incremental_dexing flag. Users should set this attribute to 0 for release binaries (e.g., to avoid accidental usage of --incremental_dexing), since incremental dexing can produce slightly larger artifacts than dx. It is an error to set this attribute to 1 for android_binary and android_test rules that have Proguard enabled, as well as for android_test rules with binary_under_test set. We are working on addressing these shortcomings so please check with us if you run into these limitations. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("incremental_dexing", TRISTATE) // Read by DexArchiveAspect's attribute extractor .nonconfigurable("AspectParameters don't support configurations.")) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(multidex) --> Whether to split code into multiple dex files.<br/> Possible values: <ul> <li><code>native</code>: Split code into multiple dex files when the dex 64K index limit is exceeded. Assumes native platform support for loading multidex classes at runtime. <em class="harmful">This works with only Android L and newer</em>.</li> <li><code>legacy</code>: Split code into multiple dex files when the dex 64K index limit is exceeded. Assumes multidex classes are loaded through application code (i.e. no native platform support).</li> <li><code>manual_main_dex</code>: Split code into multiple dex files when the dex 64K index limit is exceeded. The content of the main dex file needs to be specified by providing a list of classes in a text file using the <a href="${link android_binary.main_dex_list}">main_dex_list</a> attribute.</li> <li><code>off</code>: Compile all code to a single dex file, even if it exceeds the index limit.</li> </ul> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("multidex", STRING) .allowedValues(new AllowedValueSet(MultidexMode.getValidValues())) .value(MultidexMode.OFF.getAttributeValue())) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(main_dex_list_opts) --> Command line options to pass to the main dex list builder. Use this option to affect the classes included in the main dex list. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("main_dex_list_opts", STRING_LIST)) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(main_dex_list) --> A text file contains a list of class file names. Classes defined by those class files are put in the primary classes.dex. e.g.:<pre class="code"> android/support/multidex/MultiDex$V19.class android/support/multidex/MultiDex.class android/support/multidex/MultiDexApplication.class com/google/common/base/Objects.class </pre> Must be used with <code>multidex="manual_main_dex"</code>. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("main_dex_list", LABEL).legacyAllowAnyFileType()) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(main_dex_proguard_specs) --> Files to be used as the Proguard specifications to determine classes that must be kept in the main dex. Only allowed if the <code>multidex</code> attribute is set to <code>legacy</code>. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("main_dex_proguard_specs", LABEL_LIST).legacyAllowAnyFileType()) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(proguard_specs) --> Files to be used as Proguard specification. This file will describe the set of specifications to be used by Proguard. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("proguard_specs", LABEL_LIST).legacyAllowAnyFileType()) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(proguard_generate_mapping) --> Whether to generate Proguard mapping file. The mapping file will be generated only if <code>proguard_specs</code> is specified. This file will list the mapping between the original and obfuscated class, method, and field names. <p><em class="harmful">WARNING: If this attribute is used, the Proguard specification should contain neither <code>-dontobfuscate</code> nor <code>-printmapping</code>.</em></p> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("proguard_generate_mapping", BOOLEAN) .value(false) .nonconfigurable("value is referenced in an ImplicitOutputsFunction")) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(proguard_apply_mapping) --> File to be used as a mapping for proguard. A mapping file generated by <code>proguard_generate_mapping</code> to be re-used to apply the same mapping to a new build. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("proguard_apply_mapping", LABEL).legacyAllowAnyFileType()) /* <!-- #BLAZE_RULE($android_binary_base).ATTRIBUTE(proguard_apply_dictionary) --> File to be used as a mapping for proguard. A line separated file of "words" to pull from when renaming classes and members during obfuscation. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("proguard_apply_dictionary", LABEL).legacyAllowAnyFileType()) // TODO(mstaib): Remove this attribute and the matching flag after some cleanup of users .add( attr("legacy_native_support", TRISTATE) .value(TriState.AUTO) .undocumented("No-op, soon to be removed")) .add(attr(":extra_proguard_specs", LABEL_LIST).value(JavaSemantics.EXTRA_PROGUARD_SPECS)) .add( attr(":bytecode_optimizers", LABEL_LIST) .cfg(HOST) .value(JavaSemantics.BYTECODE_OPTIMIZERS)) // We need the C++ toolchain for every sub-configuration to get the correct linker. .add( attr(":cc_toolchain_split", LABEL) .cfg(AndroidRuleClasses.ANDROID_SPLIT_TRANSITION) .value(CppRuleClasses.ccToolchainAttribute(env))) .add(attr("rewrite_dexes_with_rex", BOOLEAN).value(false).undocumented("experimental")) /* File to be used as a package map for Rex tool that keeps the assignment of classes to dex files of a multi-dex application stable over time. Can only be used when <code>proguard_specs</code> is also specified. When <code>proguard_specs</code> is specified, but a package map isn't or there were changes, Rex suggests an updated package map that can be saved and reused for subsequent builds. */ .add(attr("rex_package_map", LABEL).legacyAllowAnyFileType().undocumented("experimental")) /* <!-- #BLAZE_RULE(android_binary).ATTRIBUTE(manifest_merger) --> Select the manifest merger to use for this rule.<br/> Possible values: <ul> <li><code>manifest_merger = "legacy"</code>: Use the legacy manifest merger. Does not allow features of the android merger like placeholder substitution and tools attributes for defining merge behavior. Removes all <code>&lt;uses-permission&gt;</code> and <code>&lt;uses-permission-sdk-23&gt;</code> tags. Performs a tag-level merge.</li> <li><code>manifest_merger = "android"</code>: Use the android manifest merger. Allows features like placeholder substitution and tools attributes for defining merge behavior. Follows the semantics from <a href="http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger"> the documentation</a> except it has been modified to also remove all <code>&lt;uses-permission&gt;</code> and <code>&lt;uses-permission-sdk-23&gt;</code> tags. Performs an attribute-level merge.</li> <li><code>manifest_merger = "auto"</code>: Merger is controlled by the <a href="../user-manual.html#flag--android_manifest_merger"> --android_manifest_merger</a> flag.</li> </ul> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("manifest_merger", STRING) .allowedValues(new AllowedValueSet(AndroidManifestMerger.getAttributeValues())) .value(AndroidManifestMerger.getRuleAttributeDefault())) /* <!-- #BLAZE_RULE(android_binary).ATTRIBUTE(manifest_values) --> A dictionary of values to be overridden in the manifest. Any instance of ${name} in the manifest will be replaced with the value corresponding to name in this dictionary. applicationId, versionCode, versionName, minSdkVersion, targetSdkVersion and maxSdkVersion will also override the corresponding attributes of the manifest and uses-sdk tags. packageName will be ignored and will be set from either applicationId if specified or the package in manifest. When manifest_merger is set to legacy, only applicationId, versionCode and versionName will have any effect. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("manifest_values", STRING_DICT)) /* <!-- #BLAZE_RULE(android_binary).ATTRIBUTE(aapt_version) --> Select the version of aapt for this rule.<br/> Possible values: <ul> <li><code>aapt_version = "aapt"</code>: Use aapt. This is the current default behaviour, and should be used for production binaries. The android_sdk rule must have an aapt binary to use this option.</li> <li><code>aapt_version = "aapt2"</code>: Use aapt2. This is the new resource packaging system that provides improved incremental resource processing, smaller apks and more. The android_sdk rule must have the aapt2 binary to use this option.</li> <li><code>aapt_version = "auto"</code>: aapt is controlled by the --android_aapt_version flag.</li> </ul> <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add( attr("aapt_version", STRING) .undocumented("experimental, b/28819519") .allowedValues(new AllowedValueSet(AndroidAaptVersion.getAttributeValues())) .value(AndroidAaptVersion.getRuleAttributeDefault())) .add( attr(AndroidFeatureFlagSetProvider.FEATURE_FLAG_ATTR, LABEL_KEYED_STRING_DICT) .undocumented("the feature flag feature has not yet been launched") .allowedRuleClasses("config_feature_flag") .allowedFileTypes() .nonconfigurable("defines an aspect of configuration") .mandatoryProviders(ImmutableList.of(ConfigFeatureFlagProvider.id()))) .add(AndroidFeatureFlagSetProvider.getWhitelistAttribute(env)) // The resource extractor is used at the binary level to extract java resources from the // deploy jar so that they can be added to the APK. .add( attr("$resource_extractor", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:resource_extractor"))) .add( attr("instruments", LABEL) .undocumented("blocked by android_instrumentation_test") .allowedRuleClasses("android_binary") .allowedFileTypes(NO_FILE)) .add( attr("$zip_filter", LABEL) .cfg(HOST) .exec() .value(env.getToolsLabel("//tools/android:zip_filter"))) .removeAttribute("data") .advertiseProvider(ApkProvider.class) .advertiseSkylarkProvider(SkylarkProviderIdentifier.forKey(JavaInfo.PROVIDER.getKey())) .build(); } @Override public Metadata getMetadata() { return RuleDefinition.Metadata.builder() .name("$android_binary_base") .type(RuleClassType.ABSTRACT) .ancestors(AndroidResourceSupportRule.class) .build(); } } /** Semantic options for the dexer's multidex behavior. */ public enum MultidexMode { // Build dexes with multidex, assuming native platform support for multidex. NATIVE, // Build dexes with multidex and implement support at the application level. LEGACY, // Build dexes with multidex, main dex list needs to be manually specified. MANUAL_MAIN_DEX, // Build all dex code into a single classes.dex file. OFF; /** Returns the attribute value that specifies this mode. */ public String getAttributeValue() { return toString().toLowerCase(); } /** * Returns the name of the output dex classes file. In multidex mode, this is an archive of * (possibly) multiple files. */ public String getOutputDexFilename() { return this == OFF ? "classes.dex" : "classes.dex.zip"; } /** Converts an attribute value to a corresponding mode. Returns null on no match. */ public static MultidexMode fromValue(String value) { for (MultidexMode mode : values()) { if (mode.getAttributeValue().equals(value)) { return mode; } } return null; } /** Enumerates valid values for the "multidex" attribute. */ public static List<String> getValidValues() { List<String> ans = Lists.newArrayList(); for (MultidexMode mode : MultidexMode.values()) { ans.add(mode.getAttributeValue()); } return ans; } } /** Definition of the {@code android_tools_defaults_jar} rule. */ public static final class AndroidToolsDefaultsJarRule implements RuleDefinition { private final Label[] compatibleWithAndroidEnvironments; public AndroidToolsDefaultsJarRule(Label... compatibleWithAndroidEnvironments) { this.compatibleWithAndroidEnvironments = compatibleWithAndroidEnvironments; } @Override public RuleClass build(Builder builder, RuleDefinitionEnvironment environment) { builder .setUndocumented() .add( attr(":android_sdk", LABEL) .allowedRuleClasses("android_sdk", "filegroup") .value(getAndroidSdkLabel(environment.getToolsLabel(DEFAULT_SDK)))); if (compatibleWithAndroidEnvironments.length > 0) { builder.compatibleWith(compatibleWithAndroidEnvironments); } return builder.build(); } @Override public Metadata getMetadata() { return Metadata.builder() .name("android_tools_defaults_jar") .ancestors(BaseRuleClasses.BaseRule.class) .factoryClass(AndroidToolsDefaultsJar.class) .build(); } } }
Reflect progress on incremental dexing in android_binary's incremental_dexing attribute documentation. RELNOTES: None. PiperOrigin-RevId: 178047799
src/main/java/com/google/devtools/build/lib/rules/android/AndroidRuleClasses.java
Reflect progress on incremental dexing in android_binary's incremental_dexing attribute documentation. RELNOTES: None.
Java
apache-2.0
799ae2c5c2d9da979644dc736ac8c1aa1f887211
0
alexcreasy/pnc,alexcreasy/pnc,rnc/pnc,jdcasey/pnc,pkocandr/pnc,jdcasey/pnc,matedo1/pnc,matejonnet/pnc,thescouser89/pnc,alexcreasy/pnc,matedo1/pnc,matedo1/pnc,project-ncl/pnc,jdcasey/pnc
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.coordinator.notifications.buildTask; import org.jboss.pnc.messaging.spi.BuildStatusChanged; import org.jboss.pnc.messaging.spi.Message; import org.jboss.pnc.messaging.spi.MessageSender; import org.jboss.pnc.messaging.spi.Status; import org.jboss.pnc.spi.BuildCoordinationStatus; import org.jboss.pnc.spi.events.BuildCoordinationStatusChangedEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.Dependent; import javax.enterprise.event.Observes; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * @author <a href="mailto:matejonnet@gmail.com">Matej Lazar</a> */ @Dependent public class BuildStatusMQNotifications { private Logger logger = LoggerFactory.getLogger(BuildStatusMQNotifications.class); final Optional<MessageSender> messageSender; @Inject public BuildStatusMQNotifications(Instance<MessageSender> messageSender) { if (messageSender.isUnsatisfied()) { logger.warn("Messaging to MQ is disabled. There is no message sender available to inject."); this.messageSender = Optional.empty(); } else { this.messageSender = Optional.of(messageSender.get()); } } public void observeEvent(@Observes BuildCoordinationStatusChangedEvent event) { logger.debug("Observed new status changed event {}.", event); messageSender.ifPresent(ms -> send(ms, event)); logger.debug("Status changed event processed {}.", event); } private void send(MessageSender ms, BuildCoordinationStatusChangedEvent event) { Status newStatus = toMqStatus(event.getNewStatus()); if (newStatus != null) { Message message = new BuildStatusChanged( toStringStatus(getOldStatus(event.getOldStatus())), toStringStatus(newStatus), event.getBuildTaskId().toString() ); ms.sendToTopic(message, prepareHeaders(event)); } } private Status getOldStatus(BuildCoordinationStatus oldStatus) { Status mqOldStatus; if (BuildCoordinationStatus.WAITING_FOR_DEPENDENCIES.equals(oldStatus)) { mqOldStatus = Status.ACCEPTED; } else if (BuildCoordinationStatus.BUILD_COMPLETED.equals(oldStatus)) { mqOldStatus = Status.BUILDING; } else { mqOldStatus = toMqStatus(oldStatus); } return mqOldStatus; } private Map<String, String> prepareHeaders(BuildCoordinationStatusChangedEvent event) { Map<String, String> headers = new HashMap<>(); headers.put("type", "BuildStateChange"); headers.put("attribute", "state"); headers.put("name", event.getBuildConfigurationName()); headers.put("configurationId", event.getBuildConfigurationId().toString()); headers.put("configurationRevision", event.getBuildConfigurationRevision().toString()); headers.put("oldStatus", toStringStatus(getOldStatus(event.getOldStatus()))); headers.put("newStatus", toStringStatus(toMqStatus(event.getNewStatus()))); return headers; } private String toStringStatus(Status status) { if (status == null) { return ""; } else { return status.lowercase(); } } /** * * @return Status or null is status is ignored */ private Status toMqStatus(BuildCoordinationStatus status) { switch (status) { case NEW: return null; case ENQUEUED: return Status.ACCEPTED; case WAITING_FOR_DEPENDENCIES: return null; case BUILDING: return Status.BUILDING; case BUILD_COMPLETED: return null; case DONE: return Status.SUCCESS; case REJECTED: return Status.REJECTED; case REJECTED_FAILED_DEPENDENCIES: return Status.REJECTED; case REJECTED_ALREADY_BUILT: return Status.REJECTED; case SYSTEM_ERROR: return Status.FAILED; case DONE_WITH_ERRORS: return Status.FAILED; case CANCELLED: return Status.CANCELED; } throw new IllegalArgumentException("Invalid status " + status); } }
build-coordinator/src/main/java/org/jboss/pnc/coordinator/notifications/buildTask/BuildStatusMQNotifications.java
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.coordinator.notifications.buildTask; import org.jboss.pnc.messaging.spi.BuildStatusChanged; import org.jboss.pnc.messaging.spi.Message; import org.jboss.pnc.messaging.spi.MessageSender; import org.jboss.pnc.messaging.spi.Status; import org.jboss.pnc.spi.BuildCoordinationStatus; import org.jboss.pnc.spi.events.BuildCoordinationStatusChangedEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.Dependent; import javax.enterprise.event.Observes; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * @author <a href="mailto:matejonnet@gmail.com">Matej Lazar</a> */ @Dependent public class BuildStatusMQNotifications { private Logger logger = LoggerFactory.getLogger(BuildStatusMQNotifications.class); final Optional<MessageSender> messageSender; @Inject public BuildStatusMQNotifications(Instance<MessageSender> messageSender) { if (messageSender.isUnsatisfied()) { logger.warn("Messaging to MQ is disabled. There is no message sender available to inject."); this.messageSender = Optional.empty(); } else { this.messageSender = Optional.of(messageSender.get()); } } public void observeEvent(@Observes BuildCoordinationStatusChangedEvent event) { logger.debug("Observed new status changed event {}.", event); messageSender.ifPresent(ms -> send(ms, event)); logger.debug("Status changed event processed {}.", event); } private void send(MessageSender ms, BuildCoordinationStatusChangedEvent event) { Status newStatus = toMqStatus(event.getNewStatus()); if (newStatus != null) { Message message = new BuildStatusChanged( toStringStatus(toMqStatus(event.getOldStatus())), toStringStatus(newStatus), event.getBuildTaskId().toString() ); ms.sendToTopic(message, prepareHeaders(event)); } } private Map<String, String> prepareHeaders(BuildCoordinationStatusChangedEvent event) { Map<String, String> headers = new HashMap<>(); headers.put("type", "BuildStateChange"); headers.put("attribute", "state"); headers.put("name", event.getBuildConfigurationName()); headers.put("configurationId", event.getBuildConfigurationId().toString()); headers.put("configurationRevision", event.getBuildConfigurationRevision().toString()); headers.put("oldStatus", toStringStatus(toMqStatus(event.getOldStatus()))); headers.put("newStatus", toStringStatus(toMqStatus(event.getNewStatus()))); return headers; } private String toStringStatus(Status status) { if (status == null) { return ""; } else { return status.lowercase(); } } /** * * @return Status or null is status is ignored */ private Status toMqStatus(BuildCoordinationStatus status) { switch (status) { case NEW: return null; case ENQUEUED: return Status.ACCEPTED; case WAITING_FOR_DEPENDENCIES: return null; case BUILDING: return Status.BUILDING; case BUILD_COMPLETED: return null; case DONE: return Status.SUCCESS; case REJECTED: return Status.REJECTED; case REJECTED_FAILED_DEPENDENCIES: return Status.REJECTED; case REJECTED_ALREADY_BUILT: return Status.REJECTED; case SYSTEM_ERROR: return Status.FAILED; case DONE_WITH_ERRORS: return Status.FAILED; case CANCELLED: return Status.CANCELED; } throw new IllegalArgumentException("Invalid status " + status); } }
Add missing status in MQ notification. (cherry picked from commit d5b6250)
build-coordinator/src/main/java/org/jboss/pnc/coordinator/notifications/buildTask/BuildStatusMQNotifications.java
Add missing status in MQ notification.
Java
apache-2.0
cc550a574ac39e04a7518ec833a88a843a3d2556
0
calvingit21/h2o-2,100star/h2o,rowhit/h2o-2,elkingtonmcb/h2o-2,rowhit/h2o-2,vbelakov/h2o,rowhit/h2o-2,h2oai/h2o,elkingtonmcb/h2o-2,h2oai/h2o-2,eg-zhang/h2o-2,eg-zhang/h2o-2,elkingtonmcb/h2o-2,vbelakov/h2o,vbelakov/h2o,h2oai/h2o-2,111t8e/h2o-2,eg-zhang/h2o-2,100star/h2o,h2oai/h2o-2,111t8e/h2o-2,elkingtonmcb/h2o-2,111t8e/h2o-2,elkingtonmcb/h2o-2,calvingit21/h2o-2,eg-zhang/h2o-2,100star/h2o,eg-zhang/h2o-2,rowhit/h2o-2,vbelakov/h2o,h2oai/h2o,111t8e/h2o-2,eg-zhang/h2o-2,eg-zhang/h2o-2,100star/h2o,elkingtonmcb/h2o-2,rowhit/h2o-2,100star/h2o,elkingtonmcb/h2o-2,h2oai/h2o-2,calvingit21/h2o-2,100star/h2o,vbelakov/h2o,h2oai/h2o,rowhit/h2o-2,calvingit21/h2o-2,h2oai/h2o,calvingit21/h2o-2,vbelakov/h2o,rowhit/h2o-2,vbelakov/h2o,vbelakov/h2o,h2oai/h2o,elkingtonmcb/h2o-2,calvingit21/h2o-2,eg-zhang/h2o-2,h2oai/h2o,h2oai/h2o-2,eg-zhang/h2o-2,calvingit21/h2o-2,elkingtonmcb/h2o-2,h2oai/h2o-2,h2oai/h2o-2,h2oai/h2o-2,rowhit/h2o-2,100star/h2o,h2oai/h2o-2,111t8e/h2o-2,111t8e/h2o-2,h2oai/h2o-2,h2oai/h2o,h2oai/h2o,111t8e/h2o-2,eg-zhang/h2o-2,100star/h2o,rowhit/h2o-2,111t8e/h2o-2,rowhit/h2o-2,calvingit21/h2o-2,h2oai/h2o,111t8e/h2o-2,elkingtonmcb/h2o-2,calvingit21/h2o-2,calvingit21/h2o-2,h2oai/h2o,vbelakov/h2o,100star/h2o,111t8e/h2o-2,vbelakov/h2o
package hex; import water.*; import water.api.*; import water.api.Request.API; import water.fvec.Chunk; import water.fvec.Vec; import water.util.Utils; import water.util.Log; import java.util.Arrays; /** * Summary of a column. */ public class Summary2 extends Iced { static final int API_WEAVER=1; // This file has auto-gen'd doc & json fields static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code. // This Request supports the HTML 'GET' command, and this is the help text // for GET. static final String DOC_GET = "Returns a summary of a fluid-vec frame"; public static final int MAX_HIST_SZ = water.parser.Enum.MAX_ENUM_SIZE; public static final double [] DEFAULT_PERCENTILES = {0.01,0.05,0.10,0.25,0.33,0.50,0.66,0.75,0.90,0.95,0.99}; public static final int NMAX = 5; // INPUTS final transient boolean _enum; final transient boolean _isInt; final transient double _min; final transient double _max; final transient String colname; // OUTPUTS // Basic info @API(help="name" ) final String colname; @API(help="type" ) final String type; // Basic stats @API(help="average" ) final double avg; @API(help="standard deviation") final double sd; @API(help="NAs" ) final double naCnt; @API(help="categories" ) final String[] domains; @API(help="bins start" ) final double start; @API(help="bin step" ) final double binsz; @API(help="histogram" ) final long [] bins; // bins for histogram @API(help="#zeros" ) long zeros; @API(help="#rows" ) public final long rows; @API(help="min elements") double [] mins; // min N elements @API(help="max elements") double [] maxs; // max N elements @API(help="percentiles" ) double [] percentileValues; public Summary2(Vec vec, String colname) { colname = colname; _enum = vec.isEnum(); _isInt = vec.isInt(); type = _enum?"Enum":_isInt?"Int":"Real"; avg = vec.mean(); sd = vec.sigma(); naCnt = vec.naCnt(); if (_enum) domains = vec.domain(); else domains = null; long len = vec.length(); rows = len - naCnt; if (_enum) { mins = MemoryManager.malloc8d(Math.min(domains.length, NMAX)); maxs = MemoryManager.malloc8d(Math.min(domains.length, NMAX)); } else { mins = MemoryManager.malloc8d((int)Math.min(len,NMAX)); maxs = MemoryManager.malloc8d((int)Math.min(len,NMAX)); } Arrays.fill(mins, Double.POSITIVE_INFINITY); Arrays.fill(maxs, Double.NEGATIVE_INFINITY); _min = vec.min();_max = vec.max(); double span = vec.max()-vec.min() + 1; if( vec.isEnum() && span < MAX_HIST_SZ ) { start = vec.min(); binsz = 1; bins = new long[(int)span]; } else { // guard against improper parse (date type) or zero c._sigma double sigma = sd; if (Double.isNaN(sigma)) sigma = 0; double b = Math.max(1e-4,3.5 * sigma/ Math.cbrt(len)); double d = Math.pow(10, Math.floor(Math.log10(b))); if (b > 20*d/3) d *= 10; else if (b > 5*d/3) d *= 5; // tweak for integers if (d < 1. && _isInt) d = 1.; binsz = d; start = binsz * Math.floor(vec.min()/binsz); int nbin = (int)Math.floor((vec.max() + (_isInt?.5:0) - start)/binsz) + 1; assert nbin > 0; bins = new long[nbin]; } } public void add(Chunk chk) { int maxmin = 0; int minmax = 0; for (int i = 0; i < chk._len; i++) { if( chk.isNA0(i) ) continue; double val = chk.at0(i); assert val >= _min : "ERROR: ON COLUMN " + colname + " VALUE " + val + " < VEC.MIN " + _min; assert val <= _max : "ERROR: ON COLUMN " + colname + " VALUE " + val + " > VEC.MAX " + _max; if (val == 0.) zeros++; // update min/max if (val < mins[mins.length-1]) { int index = Arrays.binarySearch(mins, val); if (index < 0) { index = -(index + 1); for (int j = mins.length-1; j > index; j--) mins[j] = mins[j-1]; mins[index] = val; } } if (val > maxs[0]) { int index = Arrays.binarySearch(maxs, val); if (index < 0) { index = -(index + 1); for (int j = 0; j < index-1; j++) maxs[j] = maxs[j+1]; maxs[index-1] = val; } } // update histogram long binIdx = Math.round((val-start)*1000000.0/binsz)/1000000; ++bins[(int)binIdx]; } } public Summary2 add(Summary2 other) { zeros += other.zeros; Utils.add(bins, other.bins); double[] ds = MemoryManager.malloc8d(mins.length); int i = 0, j = 0; for (int k = 0; k < ds.length; k++) ds[k] = mins[i] < other.mins[j] ? mins[i++] : other.mins[j++]; System.arraycopy(ds,0,mins,0,ds.length); i = j = maxs.length - 1; for (int k = ds.length - 1; k >= 0; k--) ds[k] = maxs[i] > other.maxs[j] ? maxs[i--] : other.maxs[j--]; System.arraycopy(ds,0,maxs,0,ds.length); return this; } // Start of each bin public double binValue(int b) { return start + b*binsz; } private void computePercentiles(){ percentileValues = new double [DEFAULT_PERCENTILES.length]; if( bins.length == 0 ) return; int k = 0; long s = 0; for(int j = 0; j < DEFAULT_PERCENTILES.length; ++j) { final double s1 = DEFAULT_PERCENTILES[j]*rows; long bc = 0; while(s1 > s+(bc = bins[k])){ s += bc; k++; } percentileValues[j] = mins[0] + k*binsz + ((binsz > 1)?0.5*binsz:0); } } // Compute majority categories for enums only public void computeMajorities() { if (!_enum) return; for (int i = 0; i < mins.length; i++) mins[i] = i; for (int i = 0; i < maxs.length; i++) maxs[i] = i; int mini = 0, maxi = 0; for( int i = 0; i < bins.length; i++ ) { if (bins[i] < bins[(int)mins[mini]]) { mins[mini] = i; for (int j = 0; j < mins.length; j++) if (bins[(int)mins[j]] > bins[(int)mins[mini]]) mini = j; } if (bins[i] > bins[(int)maxs[maxi]]) { maxs[maxi] = i; for (int j = 0; j < maxs.length; j++) if (bins[(int)maxs[j]] < bins[(int)maxs[maxi]]) maxi = j; } } for (int i = 0; i < mins.length - 1; i++) for (int j = 0; j < i; j++) if (bins[(int)mins[j]] > bins[(int)mins[j+1]]) { double t = mins[j]; mins[j] = mins[j+1]; mins[j+1] = t; } for (int i = 0; i < maxs.length - 1; i++) for (int j = 0; j < i; j++) if (bins[(int)maxs[j]] < bins[(int)maxs[j+1]]) { double t = maxs[j]; maxs[j] = maxs[j+1]; maxs[j+1] = t; } } public double percentileValue(int idx) { if( _enum ) return Double.NaN; if(percentileValues == null) computePercentiles(); return percentileValues[idx]; } @Override public String toString(){ StringBuilder res = new StringBuilder("ColumnSummary[" + start + ":" + binValue(bins.length) +", binsz=" + binsz+"]"); if( !_enum ) for( int i=0; i<DEFAULT_PERCENTILES.length; i++ ) res.append(", p("+(int)(100*DEFAULT_PERCENTILES[i])+"%)=" + percentileValue(i)); return res.toString(); } public void toHTML( Vec vec, String cname, StringBuilder sb ) { sb.append("<div class='table' id='col_" + cname + "' style='width:90%;heigth:90%;border-top-style:solid;'>" + "<div class='alert-success'><h4>Column: " + cname + " (type: " + type + ")</h4></div>\n"); if ( rows == 0 ) { sb.append("<div class='alert'>Empty column, no summary!</div></div>\n"); return; } // Base stats if( !vec.isEnum() ) { sb.append("<div style='width:100%;'><table class='table-bordered'>"); sb.append("<tr><th colspan='"+20+"' style='text-align:center;'>Base Stats</th></tr>"); sb.append("<tr>"); sb.append("<th>avg</th><td>" + Utils.p2d(avg)+"</td>"); sb.append("<th>sd</th><td>" + Utils.p2d(sd) + "</td>"); sb.append("<th>NAs</th> <td>" + naCnt + "</td>"); sb.append("<th>zeros</th><td>" + zeros + "</td>"); sb.append("<th>min[" + mins.length + "]</th>"); for( double min : mins ) { if (min == Double.POSITIVE_INFINITY) break; sb.append("<td>" + Utils.p2d(min) + "</td>"); } sb.append("<th>max[" + maxs.length + "]</th>"); for( double max : maxs ) { if (max == Double.NEGATIVE_INFINITY) continue; sb.append("<td>" + Utils.p2d(max) + "</td>"); } // End of base stats sb.append("</tr> </table>"); sb.append("</div>"); } else { // Enums sb.append("<div style='width:100%'><table class='table-bordered'>"); sb.append("<tr><th colspan='" + 4 + "' style='text-align:center;'>Base Stats</th></tr>"); sb.append("<tr><th>NAs</th> <td>" + naCnt + "</td>"); sb.append("<th>cardinality</th> <td>" + vec.domain().length + "</td></tr>"); sb.append("</table></div>"); } // Histogram final int MAX_HISTO_BINS_DISPLAYED = 1000; int len = Math.min(bins.length,MAX_HISTO_BINS_DISPLAYED); sb.append("<div style='width:100%;overflow-x:auto;'><table class='table-bordered'>"); sb.append("<tr> <th colspan="+len+" style='text-align:center'>Histogram</th></tr>"); sb.append("<tr>"); if (_enum) for( int i=0; i<len; i++ ) sb.append("<th>" + vec.domain(i) + "</th>"); else for( int i=0; i<len; i++ ) sb.append("<th>" + Utils.p2d(binValue(i)) + "</th>"); sb.append("</tr>"); sb.append("<tr>"); for( int i=0; i<len; i++ ) sb.append("<td>" + bins[i] + "</td>"); sb.append("</tr>"); sb.append("<tr>"); for( int i=0; i<len; i++ ) sb.append(String.format("<td>%.1f%%</td>",(100.0*bins[i]/rows))); sb.append("</tr>"); if( bins.length >= MAX_HISTO_BINS_DISPLAYED ) sb.append("<div class='alert'>Histogram for this column was too big and was truncated to 1000 values!</div>"); sb.append("</table></div>"); if (!vec.isEnum()) { // Percentiles sb.append("<div style='width:100%;overflow-x:auto;'><table class='table-bordered'>"); sb.append("<tr> <th colspan='" + DEFAULT_PERCENTILES.length + "' " + "style='text-align:center' " + ">Percentiles</th></tr>"); sb.append("<tr><th>Threshold(%)</th>"); for (double pc : DEFAULT_PERCENTILES) sb.append("<td>" + (int) Math.round(pc * 100) + "</td>"); sb.append("</tr>"); sb.append("<tr><th>Value</th>"); for (double pv : percentileValues) sb.append("<td>" + Utils.p2d(pv) + "</td>"); sb.append("</tr>"); sb.append("</table>"); sb.append("</div>"); } sb.append("</div>\n"); } }
src/main/java/hex/Summary2.java
package hex; import water.*; import water.api.*; import water.api.Request.API; import water.fvec.Chunk; import water.fvec.Vec; import water.util.Utils; import water.util.Log; import java.util.Arrays; /** * Summary of a column. */ public class Summary2 extends Iced { static final int API_WEAVER=1; // This file has auto-gen'd doc & json fields static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code. // This Request supports the HTML 'GET' command, and this is the help text // for GET. static final String DOC_GET = "Returns a summary of a fluid-vec frame"; public static final int MAX_HIST_SZ = water.parser.Enum.MAX_ENUM_SIZE; public static final double [] DEFAULT_PERCENTILES = {0.01,0.05,0.10,0.25,0.33,0.50,0.66,0.75,0.90,0.95,0.99}; public static final int NMAX = 5; // INPUTS final transient boolean _enum; final transient boolean _isInt; final transient double _min; final transient double _max; final transient String _colname; // OUTPUTS @API(help="categories" ) final String[] domains; @API(help="bins start" ) final double start; @API(help="bin step" ) final double binsz; @API(help="histogram" ) final long [] bins; // bins for histogram @API(help="#zeros" ) long zeros; @API(help="#rows" ) public final long rows; @API(help="min elements") double [] mins; // min N elements @API(help="max elements") double [] maxs; // max N elements @API(help="percentiles" ) double [] percentileValues; public Summary2(Vec vec, String colname) { _colname = colname; _enum = vec.isEnum(); _isInt = vec.isInt(); if (_enum) domains = vec.domain(); else domains = null; long len = vec.length(); rows = len - vec.naCnt(); if (_enum) { mins = MemoryManager.malloc8d(Math.min(domains.length, NMAX)); maxs = MemoryManager.malloc8d(Math.min(domains.length, NMAX)); } else { mins = MemoryManager.malloc8d((int)Math.min(len,NMAX)); maxs = MemoryManager.malloc8d((int)Math.min(len,NMAX)); } Arrays.fill(mins, Double.POSITIVE_INFINITY); Arrays.fill(maxs, Double.NEGATIVE_INFINITY); _min = vec.min();_max = vec.max(); double span = vec.max()-vec.min() + 1; if( vec.isEnum() && span < MAX_HIST_SZ ) { start = vec.min(); binsz = 1; bins = new long[(int)span]; } else { // guard against improper parse (date type) or zero c._sigma double sigma = vec.sigma(); if (Double.isNaN(sigma)) sigma = 0; double b = Math.max(1e-4,3.5 * sigma/ Math.cbrt(len)); double d = Math.pow(10, Math.floor(Math.log10(b))); if (b > 20*d/3) d *= 10; else if (b > 5*d/3) d *= 5; // tweak for integers if (d < 1. && _isInt) d = 1.; binsz = d; start = binsz * Math.floor(vec.min()/binsz); int nbin = (int)Math.floor((vec.max() + (_isInt?.5:0) - start)/binsz) + 1; assert nbin > 0; bins = new long[nbin]; } } public void add(Chunk chk) { int maxmin = 0; int minmax = 0; for (int i = 0; i < chk._len; i++) { if( chk.isNA0(i) ) continue; double val = chk.at0(i); assert val >= _min : "ERROR: ON COLUMN " + _colname + " VALUE " + val + " < VEC.MIN " + _min; assert val <= _max : "ERROR: ON COLUMN " + _colname + " VALUE " + val + " > VEC.MAX " + _max; if (val == 0.) zeros++; // update min/max if (val < mins[mins.length-1]) { int index = Arrays.binarySearch(mins, val); if (index < 0) { index = -(index + 1); for (int j = mins.length-1; j > index; j--) mins[j] = mins[j-1]; mins[index] = val; } } if (val > maxs[0]) { int index = Arrays.binarySearch(maxs, val); if (index < 0) { index = -(index + 1); for (int j = 0; j < index-1; j++) maxs[j] = maxs[j+1]; maxs[index-1] = val; } } // update histogram long binIdx = Math.round((val-start)*1000000.0/binsz)/1000000; ++bins[(int)binIdx]; } } public Summary2 add(Summary2 other) { zeros += other.zeros; Utils.add(bins, other.bins); double[] ds = MemoryManager.malloc8d(mins.length); int i = 0, j = 0; for (int k = 0; k < ds.length; k++) ds[k] = mins[i] < other.mins[j] ? mins[i++] : other.mins[j++]; System.arraycopy(ds,0,mins,0,ds.length); i = j = maxs.length - 1; for (int k = ds.length - 1; k >= 0; k--) ds[k] = maxs[i] > other.maxs[j] ? maxs[i--] : other.maxs[j--]; System.arraycopy(ds,0,maxs,0,ds.length); return this; } // Start of each bin public double binValue(int b) { return start + b*binsz; } private void computePercentiles(){ percentileValues = new double [DEFAULT_PERCENTILES.length]; if( bins.length == 0 ) return; int k = 0; long s = 0; for(int j = 0; j < DEFAULT_PERCENTILES.length; ++j) { final double s1 = DEFAULT_PERCENTILES[j]*rows; long bc = 0; while(s1 > s+(bc = bins[k])){ s += bc; k++; } percentileValues[j] = mins[0] + k*binsz + ((binsz > 1)?0.5*binsz:0); } } // Compute majority categories for enums only public void computeMajorities() { if (!_enum) return; for (int i = 0; i < mins.length; i++) mins[i] = i; for (int i = 0; i < maxs.length; i++) maxs[i] = i; int mini = 0, maxi = 0; for( int i = 0; i < bins.length; i++ ) { if (bins[i] < bins[(int)mins[mini]]) { mins[mini] = i; for (int j = 0; j < mins.length; j++) if (bins[(int)mins[j]] > bins[(int)mins[mini]]) mini = j; } if (bins[i] > bins[(int)maxs[maxi]]) { maxs[maxi] = i; for (int j = 0; j < maxs.length; j++) if (bins[(int)maxs[j]] < bins[(int)maxs[maxi]]) maxi = j; } } for (int i = 0; i < mins.length - 1; i++) for (int j = 0; j < i; j++) if (bins[(int)mins[j]] > bins[(int)mins[j+1]]) { double t = mins[j]; mins[j] = mins[j+1]; mins[j+1] = t; } for (int i = 0; i < maxs.length - 1; i++) for (int j = 0; j < i; j++) if (bins[(int)maxs[j]] < bins[(int)maxs[j+1]]) { double t = maxs[j]; maxs[j] = maxs[j+1]; maxs[j+1] = t; } } public double percentileValue(int idx) { if( _enum ) return Double.NaN; if(percentileValues == null) computePercentiles(); return percentileValues[idx]; } @Override public String toString(){ StringBuilder res = new StringBuilder("ColumnSummary[" + start + ":" + binValue(bins.length) +", binsz=" + binsz+"]"); if( !_enum ) for( int i=0; i<DEFAULT_PERCENTILES.length; i++ ) res.append(", p("+(int)(100*DEFAULT_PERCENTILES[i])+"%)=" + percentileValue(i)); return res.toString(); } public void toHTML( Vec vec, String cname, StringBuilder sb ) { sb.append("<div class='table' id='col_" + cname + "' style='width:90%;heigth:90%;border-top-style:solid;'>" + "<div class='alert-success'><h4>Column: " + cname + "</h4></div>\n"); if ( rows == 0 ) { sb.append("<div class='alert'>Empty column, no summary!</div></div>\n"); return; } // Base stats if( !vec.isEnum() ) { sb.append("<div style='width:100%;'><table class='table-bordered'>"); sb.append("<tr><th colspan='"+20+"' style='text-align:center;'>Base Stats</th></tr>"); sb.append("<tr>"); sb.append("<th>avg</th><td>" + Utils.p2d(vec.mean())+"</td>"); sb.append("<th>sd</th><td>" + Utils.p2d(vec.sigma()) + "</td>"); sb.append("<th>NAs</th> <td>" + vec.naCnt() + "</td>"); sb.append("<th>zeros</th><td>" + zeros + "</td>"); sb.append("<th>min[" + mins.length + "]</th>"); for( double min : mins ) { if (min == Double.POSITIVE_INFINITY) break; sb.append("<td>" + Utils.p2d(min) + "</td>"); } sb.append("<th>max[" + maxs.length + "]</th>"); for( double max : maxs ) { if (max == Double.NEGATIVE_INFINITY) continue; sb.append("<td>" + Utils.p2d(max) + "</td>"); } // End of base stats sb.append("</tr> </table>"); sb.append("</div>"); } else { // Enums sb.append("<div style='width:100%'><table class='table-bordered'>"); sb.append("<tr><th colspan='" + 4 + "' style='text-align:center;'>Base Stats</th></tr>"); sb.append("<tr><th>NAs</th> <td>" + vec.naCnt() + "</td>"); sb.append("<th>cardinality</th> <td>" + vec.domain().length + "</td></tr>"); sb.append("</table></div>"); } // Histogram final int MAX_HISTO_BINS_DISPLAYED = 1000; int len = Math.min(bins.length,MAX_HISTO_BINS_DISPLAYED); sb.append("<div style='width:100%;overflow-x:auto;'><table class='table-bordered'>"); sb.append("<tr> <th colspan="+len+" style='text-align:center'>Histogram</th></tr>"); sb.append("<tr>"); if (_enum) for( int i=0; i<len; i++ ) sb.append("<th>" + vec.domain(i) + "</th>"); else for( int i=0; i<len; i++ ) sb.append("<th>" + Utils.p2d(binValue(i)) + "</th>"); sb.append("</tr>"); sb.append("<tr>"); for( int i=0; i<len; i++ ) sb.append("<td>" + bins[i] + "</td>"); sb.append("</tr>"); sb.append("<tr>"); for( int i=0; i<len; i++ ) sb.append(String.format("<td>%.1f%%</td>",(100.0*bins[i]/rows))); sb.append("</tr>"); if( bins.length >= MAX_HISTO_BINS_DISPLAYED ) sb.append("<div class='alert'>Histogram for this column was too big and was truncated to 1000 values!</div>"); sb.append("</table></div>"); if (!vec.isEnum()) { // Percentiles sb.append("<div style='width:100%;overflow-x:auto;'><table class='table-bordered'>"); sb.append("<tr> <th colspan='" + DEFAULT_PERCENTILES.length + "' " + "style='text-align:center' " + ">Percentiles</th></tr>"); sb.append("<tr><th>Threshold(%)</th>"); for (double pc : DEFAULT_PERCENTILES) sb.append("<td>" + (int) Math.round(pc * 100) + "</td>"); sb.append("</tr>"); sb.append("<tr><th>Value</th>"); for (double pv : percentileValues) sb.append("<td>" + Utils.p2d(pv) + "</td>"); sb.append("</tr>"); sb.append("</table>"); sb.append("</div>"); } sb.append("</div>\n"); } }
updated
src/main/java/hex/Summary2.java
updated
Java
apache-2.0
abee232b17d82c8a2de6f552d422fdf076f9f18c
0
hurricup/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,allotria/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,vladmm/intellij-community,jexp/idea2,asedunov/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,semonte/intellij-community,retomerz/intellij-community,FHannes/intellij-community,da1z/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,ibinti/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,kool79/intellij-community,nicolargo/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,da1z/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,ryano144/intellij-community,petteyg/intellij-community,amith01994/intellij-community,petteyg/intellij-community,joewalnes/idea-community,blademainer/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,samthor/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,da1z/intellij-community,kdwink/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,jexp/idea2,fitermay/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,hurricup/intellij-community,diorcety/intellij-community,jagguli/intellij-community,jagguli/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,slisson/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,consulo/consulo,signed/intellij-community,youdonghai/intellij-community,allotria/intellij-community,hurricup/intellij-community,xfournet/intellij-community,fnouama/intellij-community,fitermay/intellij-community,slisson/intellij-community,apixandru/intellij-community,petteyg/intellij-community,samthor/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,kool79/intellij-community,kool79/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,retomerz/intellij-community,signed/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,retomerz/intellij-community,caot/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,caot/intellij-community,ibinti/intellij-community,ibinti/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,diorcety/intellij-community,consulo/consulo,jagguli/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,ernestp/consulo,caot/intellij-community,izonder/intellij-community,petteyg/intellij-community,kdwink/intellij-community,asedunov/intellij-community,consulo/consulo,muntasirsyed/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,robovm/robovm-studio,kool79/intellij-community,izonder/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,jexp/idea2,nicolargo/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,signed/intellij-community,nicolargo/intellij-community,caot/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,supersven/intellij-community,youdonghai/intellij-community,da1z/intellij-community,retomerz/intellij-community,petteyg/intellij-community,hurricup/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,fnouama/intellij-community,holmes/intellij-community,nicolargo/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,signed/intellij-community,caot/intellij-community,robovm/robovm-studio,hurricup/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,petteyg/intellij-community,dslomov/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,kool79/intellij-community,jexp/idea2,supersven/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,signed/intellij-community,petteyg/intellij-community,adedayo/intellij-community,adedayo/intellij-community,joewalnes/idea-community,dslomov/intellij-community,petteyg/intellij-community,robovm/robovm-studio,retomerz/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,kdwink/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,kdwink/intellij-community,FHannes/intellij-community,samthor/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,vladmm/intellij-community,supersven/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,kool79/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,semonte/intellij-community,orekyuu/intellij-community,supersven/intellij-community,kool79/intellij-community,allotria/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,apixandru/intellij-community,FHannes/intellij-community,consulo/consulo,SerCeMan/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,jexp/idea2,orekyuu/intellij-community,adedayo/intellij-community,retomerz/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,caot/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,samthor/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,da1z/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,fitermay/intellij-community,ernestp/consulo,diorcety/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,jagguli/intellij-community,semonte/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,da1z/intellij-community,samthor/intellij-community,jagguli/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,xfournet/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,allotria/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,caot/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,ernestp/consulo,caot/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,supersven/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,ryano144/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,vvv1559/intellij-community,semonte/intellij-community,supersven/intellij-community,petteyg/intellij-community,supersven/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,fnouama/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,kool79/intellij-community,joewalnes/idea-community,ryano144/intellij-community,da1z/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,holmes/intellij-community,izonder/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,caot/intellij-community,slisson/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,slisson/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,nicolargo/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,asedunov/intellij-community,jexp/idea2,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,amith01994/intellij-community,semonte/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,allotria/intellij-community,holmes/intellij-community,signed/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,semonte/intellij-community,ibinti/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,jexp/idea2,vladmm/intellij-community,xfournet/intellij-community,ernestp/consulo,blademainer/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,caot/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,semonte/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,blademainer/intellij-community,samthor/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,signed/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,retomerz/intellij-community,apixandru/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,clumsy/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,fnouama/intellij-community,xfournet/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,holmes/intellij-community,fitermay/intellij-community,ernestp/consulo,fitermay/intellij-community,adedayo/intellij-community,holmes/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,signed/intellij-community,ibinti/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,izonder/intellij-community,kdwink/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,xfournet/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,izonder/intellij-community,kool79/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,samthor/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,samthor/intellij-community,tmpgit/intellij-community,signed/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,blademainer/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,dslomov/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,xfournet/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,hurricup/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,consulo/consulo,izonder/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ernestp/consulo,Distrotech/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,tmpgit/intellij-community,izonder/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,da1z/intellij-community,clumsy/intellij-community,joewalnes/idea-community,semonte/intellij-community,ryano144/intellij-community,fnouama/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,asedunov/intellij-community
package com.intellij.codeEditor.printing; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.*; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.File; /** * */ @State( name="PrintSettings", storages= { @Storage( id="other", file = "$APP_CONFIG$/print.xml" )} ) public class PrintSettings implements PersistentStateComponent<PrintSettings>, ExportableComponent { @NonNls public String PAPER_SIZE = "A4"; public boolean COLOR_PRINTING = false; public boolean SYNTAX_PRINTING = true; public boolean PRINT_AS_GRAPHICS = true; public boolean PORTRAIT_LAYOUT = true; @NonNls public String FONT_NAME = "monospaced"; public int FONT_SIZE = 10; public boolean PRINT_LINE_NUMBERS = true; public boolean WRAP = true; public float TOP_MARGIN = 0.5f; public float BOTTOM_MARGIN = 1.0f; public float LEFT_MARGIN = 1.0f; public float RIGHT_MARGIN = 1.0f; public boolean DRAW_BORDER = true; public String FOOTER_HEADER_TEXT1 = CodeEditorBundle.message("print.header.default.line.1"); public String FOOTER_HEADER_PLACEMENT1 = HEADER; public String FOOTER_HEADER_ALIGNMENT1 = LEFT; public String FOOTER_HEADER_TEXT2 = CodeEditorBundle.message("print.header.default.line.2"); public String FOOTER_HEADER_PLACEMENT2 = FOOTER; public String FOOTER_HEADER_ALIGNMENT2 = CENTER; public int FOOTER_HEADER_FONT_SIZE = 8; @NonNls public String FOOTER_HEADER_FONT_NAME = "Arial"; public static final int PRINT_FILE = 1; public static final int PRINT_SELECTED_TEXT = 2; public static final int PRINT_DIRECTORY = 4; private int myPrintScope; private boolean myIncludeSubdirectories; @NonNls public static final String HEADER = "Header"; @NonNls public static final String FOOTER = "Footer"; @NonNls public static final String LEFT = "Left"; @NonNls public static final String CENTER = "Center"; @NonNls public static final String RIGHT = "Right"; public static PrintSettings getInstance() { return ServiceManager.getService(PrintSettings.class); } @NotNull public File[] getExportFiles() { return new File[]{PathManager.getOptionsFile("print")}; } @NotNull public String getPresentableName() { return CodeEditorBundle.message("title.print.settings"); } public int getPrintScope() { return myPrintScope; } public void setPrintScope(int printScope) { myPrintScope = printScope; } public boolean isIncludeSubdirectories() { return myIncludeSubdirectories; } public void setIncludeSubdirectories(boolean includeSubdirectories) { myIncludeSubdirectories = includeSubdirectories; } public PrintSettings getState() { return this; } public void loadState(final PrintSettings state) { XmlSerializerUtil.copyBean(state, this); } }
lang-impl/src/com/intellij/codeEditor/printing/PrintSettings.java
package com.intellij.codeEditor.printing; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.*; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.File; /** * */ @State( name="PrintSettings", storages= { @Storage( id="other", file = "$APP_CONFIG$/editor.xml" )} ) public class PrintSettings implements PersistentStateComponent<PrintSettings>, ExportableComponent { @NonNls public String PAPER_SIZE = "A4"; public boolean COLOR_PRINTING = false; public boolean SYNTAX_PRINTING = true; public boolean PRINT_AS_GRAPHICS = true; public boolean PORTRAIT_LAYOUT = true; @NonNls public String FONT_NAME = "monospaced"; public int FONT_SIZE = 10; public boolean PRINT_LINE_NUMBERS = true; public boolean WRAP = true; public float TOP_MARGIN = 0.5f; public float BOTTOM_MARGIN = 1.0f; public float LEFT_MARGIN = 1.0f; public float RIGHT_MARGIN = 1.0f; public boolean DRAW_BORDER = true; public String FOOTER_HEADER_TEXT1 = CodeEditorBundle.message("print.header.default.line.1"); public String FOOTER_HEADER_PLACEMENT1 = HEADER; public String FOOTER_HEADER_ALIGNMENT1 = LEFT; public String FOOTER_HEADER_TEXT2 = CodeEditorBundle.message("print.header.default.line.2"); public String FOOTER_HEADER_PLACEMENT2 = FOOTER; public String FOOTER_HEADER_ALIGNMENT2 = CENTER; public int FOOTER_HEADER_FONT_SIZE = 8; @NonNls public String FOOTER_HEADER_FONT_NAME = "Arial"; public static final int PRINT_FILE = 1; public static final int PRINT_SELECTED_TEXT = 2; public static final int PRINT_DIRECTORY = 4; private int myPrintScope; private boolean myIncludeSubdirectories; @NonNls public static final String HEADER = "Header"; @NonNls public static final String FOOTER = "Footer"; @NonNls public static final String LEFT = "Left"; @NonNls public static final String CENTER = "Center"; @NonNls public static final String RIGHT = "Right"; public static PrintSettings getInstance() { return ServiceManager.getService(PrintSettings.class); } @NotNull public File[] getExportFiles() { return new File[]{PathManager.getOptionsFile("print")}; } @NotNull public String getPresentableName() { return CodeEditorBundle.message("title.print.settings"); } public int getPrintScope() { return myPrintScope; } public void setPrintScope(int printScope) { myPrintScope = printScope; } public boolean isIncludeSubdirectories() { return myIncludeSubdirectories; } public void setIncludeSubdirectories(boolean includeSubdirectories) { myIncludeSubdirectories = includeSubdirectories; } public PrintSettings getState() { return this; } public void loadState(final PrintSettings state) { XmlSerializerUtil.copyBean(state, this); } }
typo, sorry
lang-impl/src/com/intellij/codeEditor/printing/PrintSettings.java
typo, sorry
Java
apache-2.0
5d88f8bc1ed903aace85b0279bc02979ef1199a1
0
realityforge/replicant,realityforge/replicant
package org.realityforge.replicant.client.transport; import arez.Disposable; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.gwt.webpoller.client.RequestFactory; import org.realityforge.gwt.webpoller.client.WebPoller; import org.realityforge.gwt.webpoller.client.WebPollerListener; import org.realityforge.gwt.webpoller.client.WebPollerListenerAdapter; import org.realityforge.replicant.shared.transport.ReplicantContext; import replicant.ChannelAddress; import replicant.Replicant; public abstract class WebPollerDataLoaderService extends AbstractDataLoaderService { protected static final int HTTP_STATUS_CODE_OK = 200; private WebPoller _webPoller; protected WebPollerDataLoaderService( @Nonnull final CacheService cacheService ) { super( cacheService ); } @Nonnull protected WebPoller createWebPoller() { final WebPoller webpoller = newWebPoller(); webpoller.setLogLevel( getWebPollerLogLevel() ); webpoller.setRequestFactory( newRequestFactory() ); webpoller.setInterRequestDuration( 0 ); webpoller.setListener( newWebPollerListener() ); return webpoller; } @Nonnull protected WebPollerListener newWebPollerListener() { return new ReplicantWebPollerListener(); } @Nonnull protected Level getWebPollerLogLevel() { return Level.FINEST; } @Nonnull protected abstract WebPoller newWebPoller(); @Nonnull protected abstract String getEndpointOffset(); protected void onSessionCreated( @Nonnull final String sessionID, @Nullable final Runnable runnable ) { setSession( new ClientSession( this, sessionID ), runnable ); scheduleDataLoad(); startPolling(); } @Override public void disconnect() { stopPolling(); super.disconnect(); } /** * Return the base url at which the replicant jaxrs resource is anchored. */ @Nonnull protected String getBaseURL() { return getSessionContext().getBaseURL() + getEndpointOffset(); } /** * Return the url to poll for replicant data stream. * * The implementation derives the url from getBaseURL(). */ @Nonnull protected String getPollURL() { return getBaseURL() + ReplicantContext.REPLICANT_URL_FRAGMENT + "?" + ReplicantContext.RECEIVE_SEQUENCE_PARAM + "=" + ensureSession().getLastRxSequence(); } /** * Return the url to session service. * * The implementation derives the url from getBaseURL(). */ @Nonnull protected String getBaseSessionURL() { return getBaseURL() + ReplicantContext.SESSION_URL_FRAGMENT; } /** * Return the url to the specific resource for specified session */ @Nonnull protected String getSessionURL() { return getBaseSessionURL() + "/" + ensureSession().getSessionID(); } /** * Return URL to the specified channel for this session. */ @Nonnull protected String getChannelURL( final int channel, @Nullable Integer subChannelId ) { return getSessionURL() + ReplicantContext.CHANNEL_URL_FRAGMENT + "/" + channel + ( null == subChannelId ? "" : "." + subChannelId ); } /** * Return URL to the specified channel, for the set of subChannelIds for this session. */ @Nonnull protected String getChannelURL( final int channel, @Nonnull List<Integer> subChannelIds ) { final String queryParam = ReplicantContext.SUB_CHANNEL_ID_PARAM + "=" + subChannelIds.stream().map( Object::toString ).collect( Collectors.joining( "," ) ); return getSessionURL() + ReplicantContext.CHANNEL_URL_FRAGMENT + "/" + channel + "?" + queryParam; } /** * Return the underlying Web Poller used by service. */ @Nonnull protected WebPoller getWebPoller() { if ( null == _webPoller ) { throw new NullPointerException( "_webPoller" ); } return _webPoller; } protected void onDisconnectError( @Nonnull final Throwable t, @Nullable final Runnable runnable ) { setSession( null, runnable ); handleInvalidDisconnect( t ); } protected void onDisconnectResponse( final int statusCode, @Nonnull final String statusText, @Nullable final Runnable action ) { final Disposable lock = context().pauseScheduler(); try { if ( HTTP_STATUS_CODE_OK == statusCode ) { setSession( null, action ); } else { setSession( null, action ); handleInvalidDisconnect( new InvalidHttpResponseException( statusCode, statusText ) ); } } finally { lock.dispose(); } } protected void onConnectResponse( final int statusCode, @Nonnull final String statusText, @Nonnull final Supplier<String> content, @Nullable final Runnable runnable ) { if ( HTTP_STATUS_CODE_OK == statusCode ) { onSessionCreated( content.get(), runnable ); } else { handleInvalidConnect( new InvalidHttpResponseException( statusCode, statusText ) ); } } protected void handleWebPollerStop() { disconnect(); } private void handlePollSuccess( final String rawJsonData ) { if ( null != rawJsonData ) { logResponse( rawJsonData ); ensureSession().enqueueDataLoad( rawJsonData ); pauseWebPoller(); } } private void logResponse( final String rawJsonData ) { if ( LOG.isLoggable( Level.INFO ) ) { final int threshold = getThresholdForResponseLogging(); final String messageData = 0 != threshold && rawJsonData.length() > threshold ? rawJsonData.substring( 0, threshold ) + "..." : rawJsonData; LOG.info( getKey() + ".Poll - Received data: " + messageData ); } } protected int getThresholdForResponseLogging() { return 300; } @Override protected void onDataLoadComplete( @Nonnull final DataLoadStatus status ) { resumeWebPoller(); super.onDataLoadComplete( status ); } protected void startPolling() { stopPolling(); _webPoller = createWebPoller(); _webPoller.start(); } @Nonnull protected abstract RequestFactory newRequestFactory(); @Override protected void doSetSession( @Nullable final ClientSession session, @Nullable final Runnable postAction ) { if ( null == session ) { stopPolling(); } super.doSetSession( session, postAction ); } protected void stopPolling() { if ( null != _webPoller ) { if ( _webPoller.isActive() ) { _webPoller.stop(); } _webPoller = null; } } protected void pauseWebPoller() { if ( null != _webPoller && _webPoller.isActive() && !_webPoller.isPaused() ) { _webPoller.pause(); } } protected void resumeWebPoller() { if ( null != _webPoller && _webPoller.isActive() && _webPoller.isPaused() ) { _webPoller.resume(); } } @Override protected void requestSubscribeToChannel( @Nonnull final ChannelAddress address, @Nullable final Object filterParameter, @Nullable final String cacheKey, @Nullable final String eTag, @Nullable final Consumer<Runnable> cacheAction, @Nonnull final Consumer<Runnable> completionAction, @Nonnull final Consumer<Runnable> failAction ) { //If eTag passed then cache action is expected. assert null == eTag || null != cacheAction; if ( isChannelTypeValid( address ) ) { getListener().onSubscribeStarted( this, address ); final Runnable onSuccess = () -> completionAction.accept( () -> getListener().onSubscribeCompleted( this, address ) ); final Runnable onCacheValid = null != cacheAction ? () -> cacheAction.accept( () -> getListener().onSubscribeCompleted( this, address ) ) : null; final Consumer<Throwable> onError = throwable -> failAction.accept( () -> getListener().onSubscribeFailed( this, address, throwable ) ); performSubscribe( address.getChannelType().ordinal(), (Serializable) address.getId(), filterParameter, cacheKey, eTag, onSuccess, onCacheValid, onError ); } else { throw new IllegalStateException(); } } private boolean isChannelTypeValid( @Nonnull final ChannelAddress address ) { return getSystemType() == address.getChannelType().getClass(); } protected void performSubscribe( final int channel, @Nullable Integer subChannelId, @Nullable final Object filterParameter, @Nullable String cacheKey, @Nullable String eTag, @Nonnull final Runnable onSuccess, @Nullable final Runnable onCacheValid, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "Subscribe", channel ), cacheKey, ( session, request ) -> doSubscribe( session, request, filterParameter, getChannelURL( channel, subChannelId ), eTag, onSuccess, onCacheValid, onError ) ); } @Override protected void requestBulkSubscribeToChannel( @Nonnull final List<ChannelAddress> addresses, @Nullable final Object filterParameter, @Nonnull final Consumer<Runnable> completionAction, @Nonnull final Consumer<Runnable> failAction ) { final ChannelAddress descriptor = addresses.get( 0 ); if ( isChannelTypeValid( descriptor ) ) { addresses.forEach( x -> getListener().onSubscribeStarted( this, x ) ); final Runnable onSuccess = () -> completionAction.accept( () -> addresses.forEach( x -> getListener().onSubscribeCompleted( this, x ) ) ); final Consumer<Throwable> onError = throwable -> failAction.accept( () -> addresses.forEach( x -> getListener().onSubscribeFailed( this, descriptor, throwable ) ) ); performBulkSubscribe( descriptor.getChannelType().ordinal(), addresses.stream().map( x -> (Serializable) x.getId() ).collect( Collectors.toList() ), filterParameter, onSuccess, onError ); } else { throw new IllegalStateException(); } } protected void performBulkSubscribe( final int channel, @Nonnull List<Integer> subChannelIds, @Nullable final Object filterParameter, @Nonnull final Runnable onSuccess, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "BulkSubscribe", channel ), null, ( session, request ) -> doSubscribe( session, request, filterParameter, getChannelURL( channel, subChannelIds ), null, onSuccess, null, onError ) ); } @Override protected void requestUpdateSubscription( @Nonnull final ChannelAddress descriptor, @Nonnull final Object filterParameter, @Nonnull final Consumer<Runnable> completionAction, @Nonnull final Consumer<Runnable> failAction ) { if ( isChannelTypeValid( descriptor ) ) { getListener().onSubscriptionUpdateStarted( this, descriptor ); final Runnable onSuccess = () -> completionAction.accept( () -> getListener().onSubscriptionUpdateCompleted( this, descriptor ) ); final Consumer<Throwable> onError = throwable -> failAction.accept( () -> getListener().onSubscriptionUpdateFailed( this, descriptor, throwable ) ); performUpdateSubscription( descriptor.getChannelType().ordinal(), (Serializable) descriptor.getId(), filterParameter, onSuccess, onError ); } else { throw new IllegalStateException(); } } protected void performUpdateSubscription( final int channel, @Nullable Integer subChannelId, @Nullable final Object filterParameter, @Nonnull final Runnable onSuccess, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "SubscriptionUpdate", channel ), null, ( session, request ) -> doSubscribe( session, request, filterParameter, getChannelURL( channel, subChannelId ), null, onSuccess, null, onError ) ); } protected void requestBulkUpdateSubscription( @Nonnull List<ChannelAddress> descriptors, @Nonnull Object filterParameter, @Nonnull Consumer<Runnable> completionAction, @Nonnull Consumer<Runnable> failAction ) { final ChannelAddress descriptor = descriptors.get( 0 ); if ( isChannelTypeValid( descriptor ) ) { descriptors.forEach( x -> getListener().onSubscriptionUpdateStarted( this, x ) ); final Runnable onSuccess = () -> completionAction.accept( () -> descriptors.forEach( x -> getListener().onSubscriptionUpdateCompleted( this, descriptor ) ) ); final Consumer<Throwable> onError = throwable -> failAction.accept( () -> descriptors.forEach( x -> getListener().onSubscriptionUpdateFailed( this, descriptor, throwable ) ) ); performBulkUpdateSubscription( descriptor.getChannelType().ordinal(), descriptors.stream().map( x -> (Serializable) x.getId() ).collect( Collectors.toList() ), filterParameter, onSuccess, onError ); } else { throw new IllegalStateException(); } } protected void performBulkUpdateSubscription( final int channel, @Nonnull List<Integer> subChannelIds, @Nullable final Object filterParameter, @Nonnull final Runnable onSuccess, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "BulkSubscriptionUpdate", channel ), null, ( session, request ) -> doSubscribe( session, request, filterParameter, getChannelURL( channel, subChannelIds ), null, onSuccess, null, onError ) ); } @Override protected void requestUnsubscribeFromChannel( @Nonnull final ChannelAddress address, @Nonnull final Consumer<Runnable> completionAction, @Nonnull final Consumer<Runnable> failAction ) { if ( isChannelTypeValid( address ) ) { onUnsubscribeStarted( address ); final Consumer<Throwable> onError = error -> failAction.accept( () -> onUnsubscribeFailed( address, error ) ); final Runnable onSuccess = () -> completionAction.accept( () -> onUnsubscribeCompleted( address ) ); performUnsubscribe( address.getChannelType().ordinal(), address.getId(), onSuccess, onError ); } else { throw new IllegalStateException(); } } protected void performUnsubscribe( final int channel, @Nullable Integer subChannelId, @Nonnull final Runnable onSuccess, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "Unsubscribe", channel ), null, ( session, request ) -> doUnsubscribe( session, request, getChannelURL( channel, subChannelId ), onSuccess, onError ) ); } @Override protected void requestBulkUnsubscribeFromChannel( @Nonnull final List<ChannelAddress> addresses, @Nonnull final Consumer<Runnable> completionAction, @Nonnull final Consumer<Runnable> failAction ) { final ChannelAddress descriptor = addresses.get( 0 ); if ( isChannelTypeValid( descriptor ) ) { addresses.forEach( x -> getListener().onUnsubscribeStarted( this, x ) ); final Runnable onSuccess = () -> completionAction.accept( () -> addresses.forEach( x -> getListener().onUnsubscribeCompleted( this, x ) ) ); final Consumer<Throwable> onError = throwable -> failAction.accept( () -> addresses.forEach( x -> getListener().onUnsubscribeFailed( this, descriptor, throwable ) ) ); performBulkUnsubscribe( descriptor.getChannelType().ordinal(), addresses.stream().map( x -> (Serializable) x.getId() ).collect( Collectors.toList() ), onSuccess, onError ); } else { throw new IllegalStateException(); } } protected void performBulkUnsubscribe( final int channel, @Nonnull List<Integer> subChannelIds, @Nonnull final Runnable onSuccess, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "BulkUnsubscribe", channel ), null, ( session, request ) -> doUnsubscribe( session, request, getChannelURL( channel, subChannelIds ), onSuccess, onError ) ); } protected abstract void doSubscribe( @Nullable ClientSession session, @Nullable RequestEntry request, @Nullable Object filterParameter, @Nonnull String channelURL, @Nullable String eTag, @Nonnull Runnable onSuccess, @Nullable Runnable onCacheValid, @Nonnull Consumer<Throwable> onError ); protected abstract void doUnsubscribe( @Nullable ClientSession session, @Nullable RequestEntry request, @Nonnull String channelURL, @Nonnull Runnable onSuccess, @Nonnull Consumer<Throwable> onError ); @Nullable private String toRequestKey( @Nonnull final String requestType, final int channel ) { return Replicant.shouldRecordRequestKey() ? requestType + ":" + getSystemType().getEnumConstants()[ channel ] : null; } private class ReplicantWebPollerListener extends WebPollerListenerAdapter { @Override public void onMessage( @Nonnull final WebPoller webPoller, @Nonnull final Map<String, String> context, @Nonnull final String data ) { handlePollSuccess( data ); } @Override public void onError( @Nonnull final WebPoller webPoller, @Nonnull final Throwable exception ) { getListener().onPollFailure( WebPollerDataLoaderService.this, exception ); } @Override public void onStop( @Nonnull final WebPoller webPoller ) { handleWebPollerStop(); } } }
client/src/main/java/org/realityforge/replicant/client/transport/WebPollerDataLoaderService.java
package org.realityforge.replicant.client.transport; import arez.Disposable; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.gwt.webpoller.client.RequestFactory; import org.realityforge.gwt.webpoller.client.WebPoller; import org.realityforge.gwt.webpoller.client.WebPollerListener; import org.realityforge.gwt.webpoller.client.WebPollerListenerAdapter; import org.realityforge.replicant.shared.transport.ReplicantContext; import replicant.ChannelAddress; import replicant.Replicant; public abstract class WebPollerDataLoaderService extends AbstractDataLoaderService { protected static final int HTTP_STATUS_CODE_OK = 200; private WebPoller _webPoller; protected WebPollerDataLoaderService( @Nonnull final CacheService cacheService ) { super( cacheService ); } @Nonnull protected WebPoller createWebPoller() { final WebPoller webpoller = newWebPoller(); webpoller.setLogLevel( getWebPollerLogLevel() ); webpoller.setRequestFactory( newRequestFactory() ); webpoller.setInterRequestDuration( 0 ); webpoller.setListener( newWebPollerListener() ); return webpoller; } @Nonnull protected WebPollerListener newWebPollerListener() { return new ReplicantWebPollerListener(); } @Nonnull protected Level getWebPollerLogLevel() { return Level.FINEST; } @Nonnull protected abstract WebPoller newWebPoller(); @Nonnull protected abstract String getEndpointOffset(); protected void onSessionCreated( @Nonnull final String sessionID, @Nullable final Runnable runnable ) { setSession( new ClientSession( this, sessionID ), runnable ); scheduleDataLoad(); startPolling(); } @Override public void disconnect() { stopPolling(); super.disconnect(); } /** * Return the base url at which the replicant jaxrs resource is anchored. */ @Nonnull protected String getBaseURL() { return getSessionContext().getBaseURL() + getEndpointOffset(); } /** * Return the url to poll for replicant data stream. * * The implementation derives the url from getBaseURL(). */ @Nonnull protected String getPollURL() { return getBaseURL() + ReplicantContext.REPLICANT_URL_FRAGMENT + "?" + ReplicantContext.RECEIVE_SEQUENCE_PARAM + "=" + ensureSession().getLastRxSequence(); } /** * Return the url to session service. * * The implementation derives the url from getBaseURL(). */ @Nonnull protected String getBaseSessionURL() { return getBaseURL() + ReplicantContext.SESSION_URL_FRAGMENT; } /** * Return the url to the specific resource for specified session */ @Nonnull protected String getSessionURL() { return getBaseSessionURL() + "/" + ensureSession().getSessionID(); } /** * Return URL to the specified channel for this session. */ @Nonnull protected String getChannelURL( final int channel, @Nullable Serializable subChannelID ) { return getSessionURL() + ReplicantContext.CHANNEL_URL_FRAGMENT + "/" + channel + ( null == subChannelID ? "" : "." + subChannelID ); } /** * Return URL to the specified channel, for the set of subChannelIDs for this session. */ @Nonnull protected String getChannelURL( final int channel, @Nonnull List<Serializable> subChannelIDs ) { final String queryParam = ReplicantContext.SUB_CHANNEL_ID_PARAM + "=" + subChannelIDs.stream().map( Object::toString ).collect( Collectors.joining( "," ) ); return getSessionURL() + ReplicantContext.CHANNEL_URL_FRAGMENT + "/" + channel + "?" + queryParam; } /** * Return the underlying Web Poller used by service. */ @Nonnull protected WebPoller getWebPoller() { if ( null == _webPoller ) { throw new NullPointerException( "_webPoller" ); } return _webPoller; } protected void onDisconnectError( @Nonnull final Throwable t, @Nullable final Runnable runnable ) { setSession( null, runnable ); handleInvalidDisconnect( t ); } protected void onDisconnectResponse( final int statusCode, @Nonnull final String statusText, @Nullable final Runnable action ) { final Disposable lock = context().pauseScheduler(); try { if ( HTTP_STATUS_CODE_OK == statusCode ) { setSession( null, action ); } else { setSession( null, action ); handleInvalidDisconnect( new InvalidHttpResponseException( statusCode, statusText ) ); } } finally { lock.dispose(); } } protected void onConnectResponse( final int statusCode, @Nonnull final String statusText, @Nonnull final Supplier<String> content, @Nullable final Runnable runnable ) { if ( HTTP_STATUS_CODE_OK == statusCode ) { onSessionCreated( content.get(), runnable ); } else { handleInvalidConnect( new InvalidHttpResponseException( statusCode, statusText ) ); } } protected void handleWebPollerStop() { disconnect(); } private void handlePollSuccess( final String rawJsonData ) { if ( null != rawJsonData ) { logResponse( rawJsonData ); ensureSession().enqueueDataLoad( rawJsonData ); pauseWebPoller(); } } private void logResponse( final String rawJsonData ) { if ( LOG.isLoggable( Level.INFO ) ) { final int threshold = getThresholdForResponseLogging(); final String messageData = 0 != threshold && rawJsonData.length() > threshold ? rawJsonData.substring( 0, threshold ) + "..." : rawJsonData; LOG.info( getKey() + ".Poll - Received data: " + messageData ); } } protected int getThresholdForResponseLogging() { return 300; } @Override protected void onDataLoadComplete( @Nonnull final DataLoadStatus status ) { resumeWebPoller(); super.onDataLoadComplete( status ); } protected void startPolling() { stopPolling(); _webPoller = createWebPoller(); _webPoller.start(); } @Nonnull protected abstract RequestFactory newRequestFactory(); @Override protected void doSetSession( @Nullable final ClientSession session, @Nullable final Runnable postAction ) { if ( null == session ) { stopPolling(); } super.doSetSession( session, postAction ); } protected void stopPolling() { if ( null != _webPoller ) { if ( _webPoller.isActive() ) { _webPoller.stop(); } _webPoller = null; } } protected void pauseWebPoller() { if ( null != _webPoller && _webPoller.isActive() && !_webPoller.isPaused() ) { _webPoller.pause(); } } protected void resumeWebPoller() { if ( null != _webPoller && _webPoller.isActive() && _webPoller.isPaused() ) { _webPoller.resume(); } } @Override protected void requestSubscribeToChannel( @Nonnull final ChannelAddress address, @Nullable final Object filterParameter, @Nullable final String cacheKey, @Nullable final String eTag, @Nullable final Consumer<Runnable> cacheAction, @Nonnull final Consumer<Runnable> completionAction, @Nonnull final Consumer<Runnable> failAction ) { //If eTag passed then cache action is expected. assert null == eTag || null != cacheAction; if ( isChannelTypeValid( address ) ) { getListener().onSubscribeStarted( this, address ); final Runnable onSuccess = () -> completionAction.accept( () -> getListener().onSubscribeCompleted( this, address ) ); final Runnable onCacheValid = null != cacheAction ? () -> cacheAction.accept( () -> getListener().onSubscribeCompleted( this, address ) ) : null; final Consumer<Throwable> onError = throwable -> failAction.accept( () -> getListener().onSubscribeFailed( this, address, throwable ) ); performSubscribe( address.getChannelType().ordinal(), (Serializable) address.getId(), filterParameter, cacheKey, eTag, onSuccess, onCacheValid, onError ); } else { throw new IllegalStateException(); } } private boolean isChannelTypeValid( @Nonnull final ChannelAddress address ) { return getSystemType() == address.getChannelType().getClass(); } protected void performSubscribe( final int channel, @Nullable Serializable subChannelID, @Nullable final Object filterParameter, @Nullable String cacheKey, @Nullable String eTag, @Nonnull final Runnable onSuccess, @Nullable final Runnable onCacheValid, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "Subscribe", channel ), cacheKey, ( session, request ) -> doSubscribe( session, request, filterParameter, getChannelURL( channel, subChannelID ), eTag, onSuccess, onCacheValid, onError ) ); } @Override protected void requestBulkSubscribeToChannel( @Nonnull final List<ChannelAddress> addresses, @Nullable final Object filterParameter, @Nonnull final Consumer<Runnable> completionAction, @Nonnull final Consumer<Runnable> failAction ) { final ChannelAddress descriptor = addresses.get( 0 ); if ( isChannelTypeValid( descriptor ) ) { addresses.forEach( x -> getListener().onSubscribeStarted( this, x ) ); final Runnable onSuccess = () -> completionAction.accept( () -> addresses.forEach( x -> getListener().onSubscribeCompleted( this, x ) ) ); final Consumer<Throwable> onError = throwable -> failAction.accept( () -> addresses.forEach( x -> getListener().onSubscribeFailed( this, descriptor, throwable ) ) ); performBulkSubscribe( descriptor.getChannelType().ordinal(), addresses.stream().map( x -> (Serializable) x.getId() ).collect( Collectors.toList() ), filterParameter, onSuccess, onError ); } else { throw new IllegalStateException(); } } protected void performBulkSubscribe( final int channel, @Nonnull List<Serializable> subChannelIDs, @Nullable final Object filterParameter, @Nonnull final Runnable onSuccess, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "BulkSubscribe", channel ), null, ( session, request ) -> doSubscribe( session, request, filterParameter, getChannelURL( channel, subChannelIDs ), null, onSuccess, null, onError ) ); } @Override protected void requestUpdateSubscription( @Nonnull final ChannelAddress descriptor, @Nonnull final Object filterParameter, @Nonnull final Consumer<Runnable> completionAction, @Nonnull final Consumer<Runnable> failAction ) { if ( isChannelTypeValid( descriptor ) ) { getListener().onSubscriptionUpdateStarted( this, descriptor ); final Runnable onSuccess = () -> completionAction.accept( () -> getListener().onSubscriptionUpdateCompleted( this, descriptor ) ); final Consumer<Throwable> onError = throwable -> failAction.accept( () -> getListener().onSubscriptionUpdateFailed( this, descriptor, throwable ) ); performUpdateSubscription( descriptor.getChannelType().ordinal(), (Serializable) descriptor.getId(), filterParameter, onSuccess, onError ); } else { throw new IllegalStateException(); } } protected void performUpdateSubscription( final int channel, @Nullable Serializable subChannelID, @Nullable final Object filterParameter, @Nonnull final Runnable onSuccess, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "SubscriptionUpdate", channel ), null, ( session, request ) -> doSubscribe( session, request, filterParameter, getChannelURL( channel, subChannelID ), null, onSuccess, null, onError ) ); } protected void requestBulkUpdateSubscription( @Nonnull List<ChannelAddress> descriptors, @Nonnull Object filterParameter, @Nonnull Consumer<Runnable> completionAction, @Nonnull Consumer<Runnable> failAction ) { final ChannelAddress descriptor = descriptors.get( 0 ); if ( isChannelTypeValid( descriptor ) ) { descriptors.forEach( x -> getListener().onSubscriptionUpdateStarted( this, x ) ); final Runnable onSuccess = () -> completionAction.accept( () -> descriptors.forEach( x -> getListener().onSubscriptionUpdateCompleted( this, descriptor ) ) ); final Consumer<Throwable> onError = throwable -> failAction.accept( () -> descriptors.forEach( x -> getListener().onSubscriptionUpdateFailed( this, descriptor, throwable ) ) ); performBulkUpdateSubscription( descriptor.getChannelType().ordinal(), descriptors.stream().map( x -> (Serializable) x.getId() ).collect( Collectors.toList() ), filterParameter, onSuccess, onError ); } else { throw new IllegalStateException(); } } protected void performBulkUpdateSubscription( final int channel, @Nonnull List<Serializable> subChannelIDs, @Nullable final Object filterParameter, @Nonnull final Runnable onSuccess, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "BulkSubscriptionUpdate", channel ), null, ( session, request ) -> doSubscribe( session, request, filterParameter, getChannelURL( channel, subChannelIDs ), null, onSuccess, null, onError ) ); } @Override protected void requestUnsubscribeFromChannel( @Nonnull final ChannelAddress address, @Nonnull final Consumer<Runnable> completionAction, @Nonnull final Consumer<Runnable> failAction ) { if ( isChannelTypeValid( address ) ) { getListener().onUnsubscribeStarted( this, address ); final Consumer<Throwable> onError = throwable -> failAction.accept( () -> getListener().onUnsubscribeFailed( this, address, throwable ) ); final Runnable onSuccess = () -> completionAction.accept( () -> getListener().onUnsubscribeCompleted( this, address ) ); final int channelId = address.getChannelType().ordinal(); final Serializable subChannelId = (Serializable) address.getId(); performUnsubscribe( channelId, subChannelId, onSuccess, onError ); } else { throw new IllegalStateException(); } } protected void performUnsubscribe( final int channel, @Nullable Serializable subChannelId, @Nonnull final Runnable onSuccess, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "Unsubscribe", channel ), null, ( session, request ) -> doUnsubscribe( session, request, getChannelURL( channel, subChannelId ), onSuccess, onError ) ); } @Override protected void requestBulkUnsubscribeFromChannel( @Nonnull final List<ChannelAddress> addresses, @Nonnull final Consumer<Runnable> completionAction, @Nonnull final Consumer<Runnable> failAction ) { final ChannelAddress descriptor = addresses.get( 0 ); if ( isChannelTypeValid( descriptor ) ) { addresses.forEach( x -> getListener().onUnsubscribeStarted( this, x ) ); final Runnable onSuccess = () -> completionAction.accept( () -> addresses.forEach( x -> getListener().onUnsubscribeCompleted( this, x ) ) ); final Consumer<Throwable> onError = throwable -> failAction.accept( () -> addresses.forEach( x -> getListener().onUnsubscribeFailed( this, descriptor, throwable ) ) ); performBulkUnsubscribe( descriptor.getChannelType().ordinal(), addresses.stream().map( x -> (Serializable) x.getId() ).collect( Collectors.toList() ), onSuccess, onError ); } else { throw new IllegalStateException(); } } protected void performBulkUnsubscribe( final int channel, @Nonnull List<Serializable> subChannelIDs, @Nonnull final Runnable onSuccess, @Nonnull final Consumer<Throwable> onError ) { getSessionContext().request( toRequestKey( "BulkUnsubscribe", channel ), null, ( session, request ) -> doUnsubscribe( session, request, getChannelURL( channel, subChannelIDs ), onSuccess, onError ) ); } protected abstract void doSubscribe( @Nullable ClientSession session, @Nullable RequestEntry request, @Nullable Object filterParameter, @Nonnull String channelURL, @Nullable String eTag, @Nonnull Runnable onSuccess, @Nullable Runnable onCacheValid, @Nonnull Consumer<Throwable> onError ); protected abstract void doUnsubscribe( @Nullable ClientSession session, @Nullable RequestEntry request, @Nonnull String channelURL, @Nonnull Runnable onSuccess, @Nonnull Consumer<Throwable> onError ); @Nullable private String toRequestKey( @Nonnull final String requestType, final int channel ) { return Replicant.shouldRecordRequestKey() ? requestType + ":" + getSystemType().getEnumConstants()[ channel ] : null; } private class ReplicantWebPollerListener extends WebPollerListenerAdapter { @Override public void onMessage( @Nonnull final WebPoller webPoller, @Nonnull final Map<String, String> context, @Nonnull final String data ) { handlePollSuccess( data ); } @Override public void onError( @Nonnull final WebPoller webPoller, @Nonnull final Throwable exception ) { getListener().onPollFailure( WebPollerDataLoaderService.this, exception ); } @Override public void onStop( @Nonnull final WebPoller webPoller ) { handleWebPollerStop(); } } }
SubChannelIDs are only integers so remove reference to Serializable and update variable names appropriately
client/src/main/java/org/realityforge/replicant/client/transport/WebPollerDataLoaderService.java
SubChannelIDs are only integers so remove reference to Serializable and update variable names appropriately
Java
apache-2.0
bea7bf97a584b2ca1eed971b7f1dc07085961b9b
0
jnidzwetzki/bboxdb,jnidzwetzki/scalephant,jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb
/******************************************************************************* * * Copyright (C) 2015-2021 the BBoxDB 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 org.bboxdb.experiments; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.stream.Stream; import org.bboxdb.commons.MathUtil; import org.bboxdb.commons.math.GeoJsonPolygon; import org.bboxdb.storage.entity.Tuple; import org.bboxdb.tools.FileLineIndex; import org.bboxdb.tools.converter.tuple.ADSBTupleBuilder2D; import org.bboxdb.tools.converter.tuple.ADSBTupleBuilder3D; import org.bboxdb.tools.converter.tuple.BerlinModTupleBuilder; import org.bboxdb.tools.converter.tuple.GeoJSONTupleBuilder; import org.bboxdb.tools.converter.tuple.TupleBuilder; import org.bboxdb.tools.converter.tuple.TupleBuilderFactory; public class DetermineDistributionStateSize implements Runnable { /** * The input file */ private final File inputFile; /** * The tuple factory */ private final TupleBuilder tupleBuilder; /** * The amount of processed lines */ private long lineNumber; /** * The last read file */ private String fileLine; /** * The time the lastWatermark is generated */ private long lastWatermarkGenerated; /** * The distribution state */ private final Map<String, Long> distributionState; public DetermineDistributionStateSize(final File inputFile, final TupleBuilder tupleFactory) { this.inputFile = inputFile; this.tupleBuilder = tupleFactory; this.distributionState = new HashMap<>(); this.lineNumber = 0; this.lastWatermarkGenerated = 0; this.fileLine = null; } @Override public void run() { System.out.println("#########################"); System.out.println("## Input file: " + inputFile); final long linesInInput = determineLinesInInput(); System.out.println("## Lines in input: " + linesInInput); final long stateAfterLines = linesInInput / 20; System.out.println("## State after lines: " + stateAfterLines); System.out.println("#########################"); for(int invalidateAfterGenerations = 0; invalidateAfterGenerations < 10; invalidateAfterGenerations++) { distributionState.clear(); System.out.println("#########################"); System.out.println("## Invaliate after: " + invalidateAfterGenerations); System.out.println("## % input \t entries \t size in byte"); try(final Stream<String> fileStream = Files.lines(Paths.get(inputFile.getAbsolutePath()))) { lineNumber = 1; Tuple lastTuple = null; long watermarkGeneration = 0; for (final Iterator<String> iterator = fileStream.iterator(); iterator.hasNext();) { fileLine = iterator.next(); final Tuple tuple = tupleBuilder.buildTuple(fileLine, Long.toString(lineNumber)); if(tuple != null) { final boolean watermarkCreated = isWatermarkCreated(lastTuple, tuple); distributionState.put(tuple.getKey(), watermarkGeneration); if(watermarkCreated) { watermarkGeneration++; cleanupDistributionStructure(watermarkGeneration, invalidateAfterGenerations); } lastTuple = tuple; } if(lineNumber % (stateAfterLines) == 0) { final double percent = ((double) lineNumber / (double) linesInInput) * 100.0; final double roundPercent = MathUtil.round(percent, 0); final long stateSize = determineStateSize(); System.out.println(roundPercent + "\t" + distributionState.size() + "\t" + stateSize); } lineNumber++; } System.out.println("#########################\n\n"); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } } /** * Cleanup distribution structure * @param watermarkGeneration * @param invalidateAfterGenerations */ private void cleanupDistributionStructure(final long watermarkGeneration, final long invalidateAfterGenerations) { if(invalidateAfterGenerations == 0) { return; } distributionState .entrySet() .removeIf(e -> watermarkGeneration - invalidateAfterGenerations <= e.getValue()); } /** * Is a watermark generated * @param lastTuple * @param tuple * @return */ private boolean isWatermarkCreated(final Tuple lastTuple, final Tuple tuple) { if(lastTuple == null) { return false; } if(tupleBuilder instanceof ADSBTupleBuilder2D || tupleBuilder instanceof ADSBTupleBuilder3D) { final GeoJsonPolygon polygonOld = GeoJsonPolygon.fromGeoJson(new String(lastTuple.getDataBytes())); final GeoJsonPolygon polygonNew = GeoJsonPolygon.fromGeoJson(new String(tuple.getDataBytes())); return (polygonOld.getId() > polygonNew.getId()); } if(tupleBuilder instanceof BerlinModTupleBuilder) { final long newTimestamp = tuple.getVersionTimestamp(); if(lastWatermarkGenerated == 0) { lastWatermarkGenerated = newTimestamp; return false; } if(lastWatermarkGenerated + 60 < newTimestamp) { lastWatermarkGenerated = newTimestamp; return true; } return false; } if(tupleBuilder instanceof GeoJSONTupleBuilder) { final GeoJsonPolygon polygonNew = GeoJsonPolygon.fromGeoJson(new String(tuple.getDataBytes())); final String newTimestampString = polygonNew.getProperties().getOrDefault("TimestampParsed", "-1"); final long newTimestamp = MathUtil.tryParseLongOrExit(newTimestampString, () -> "Unable to parse: " + newTimestampString); if(lastWatermarkGenerated == 0) { lastWatermarkGenerated = newTimestamp; return false; } if(lastWatermarkGenerated + 60 < newTimestamp) { lastWatermarkGenerated = newTimestamp; return true; } return false; } System.out.println("Unsupported tuple builder: " + tupleBuilder); System.exit(1); return false; } /** * Determine the size of the distribution state * @return */ private long determineStateSize() { long size = 0; for(Map.Entry<String, Long> entry : distributionState.entrySet()) { size = size + entry.getKey().getBytes().length; size = size + 8; } return size; } /** * Determine the lines of the file * @return * @throws IOException */ private long determineLinesInInput() { final String filename = inputFile.getAbsolutePath(); try(FileLineIndex fli = new FileLineIndex(filename)) { System.out.format("Indexing %s%n", filename); fli.indexFile(); return fli.getIndexedLines(); } catch (IOException e) { e.printStackTrace(); System.exit(1); return -1; } } /*** * Main * Main * Main * Main * Main */ public static void main(final String[] args) { if(args.length != 2) { System.err.println("Usage: <Class> <Filename> <Format>"); System.exit(1); } final String filename = args[0]; final String format = args[1]; // Check file final File inputFile = new File(filename); if(! inputFile.isFile()) { System.err.println("Unable to open file: " + filename); System.exit(1); } final TupleBuilder tupleFactory = TupleBuilderFactory.getBuilderForFormat(format); final DetermineDistributionStateSize determineDistributionStateSize = new DetermineDistributionStateSize(inputFile, tupleFactory); determineDistributionStateSize.run(); } }
bboxdb-experiments/src/main/java/org/bboxdb/experiments/DetermineDistributionStateSize.java
/******************************************************************************* * * Copyright (C) 2015-2021 the BBoxDB 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 org.bboxdb.experiments; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.stream.Stream; import org.bboxdb.commons.MathUtil; import org.bboxdb.commons.math.GeoJsonPolygon; import org.bboxdb.storage.entity.Tuple; import org.bboxdb.tools.FileLineIndex; import org.bboxdb.tools.converter.tuple.ADSBTupleBuilder2D; import org.bboxdb.tools.converter.tuple.ADSBTupleBuilder3D; import org.bboxdb.tools.converter.tuple.BerlinModTupleBuilder; import org.bboxdb.tools.converter.tuple.GeoJSONTupleBuilder; import org.bboxdb.tools.converter.tuple.TupleBuilder; import org.bboxdb.tools.converter.tuple.TupleBuilderFactory; public class DetermineDistributionStateSize implements Runnable { /** * The input file */ private final File inputFile; /** * The tuple factory */ private final TupleBuilder tupleBuilder; /** * The amount of processed lines */ private long lineNumber; /** * The last read file */ private String fileLine; /** * The time the lastWatermark is generated */ private long lastWatermarkGenerated; /** * The distribution state */ private final Map<String, Long> distributionState; public DetermineDistributionStateSize(final File inputFile, final TupleBuilder tupleFactory) { this.inputFile = inputFile; this.tupleBuilder = tupleFactory; this.distributionState = new HashMap<>(); this.lineNumber = 0; this.lastWatermarkGenerated = 0; this.fileLine = null; } @Override public void run() { System.out.println("#########################"); System.out.println("## Input file: " + inputFile); final long linesInInput = determineLinesInInput(); System.out.println("## Lines in input: " + linesInInput); final long stateAfterLines = linesInInput / 20; System.out.println("## State after lines: " + stateAfterLines); System.out.println("#########################"); for(int invalidateAfterGenerations = 0; invalidateAfterGenerations < 10; invalidateAfterGenerations++) { System.out.println("#########################"); System.out.println("## Invaliate after: " + invalidateAfterGenerations); System.out.println("## % input \t entries \t size in byte"); try(final Stream<String> fileStream = Files.lines(Paths.get(inputFile.getAbsolutePath()))) { lineNumber = 1; Tuple lastTuple = null; long watermarkGeneration = 0; for (final Iterator<String> iterator = fileStream.iterator(); iterator.hasNext();) { fileLine = iterator.next(); final Tuple tuple = tupleBuilder.buildTuple(fileLine, Long.toString(lineNumber)); if(tuple != null) { final boolean watermarkCreated = isWatermarkCreated(lastTuple, tuple); distributionState.put(tuple.getKey(), watermarkGeneration); if(watermarkCreated) { watermarkGeneration++; cleanupDistributionStructure(watermarkGeneration, invalidateAfterGenerations); } lastTuple = tuple; } if(lineNumber % (stateAfterLines) == 0) { final double percent = ((double) lineNumber / (double) linesInInput) * 100.0; final double roundPercent = MathUtil.round(percent, 0); final long stateSize = determineStateSize(); System.out.println(roundPercent + "\t" + distributionState.size() + "\t" + stateSize); } lineNumber++; } System.out.println("#########################\n\n"); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } } /** * Cleanup distribution structure * @param watermarkGeneration * @param invalidateAfterGenerations */ private void cleanupDistributionStructure(final long watermarkGeneration, final long invalidateAfterGenerations) { if(invalidateAfterGenerations == 0) { return; } distributionState .entrySet() .removeIf(e -> watermarkGeneration - invalidateAfterGenerations <= e.getValue()); } /** * Is a watermark generated * @param lastTuple * @param tuple * @return */ private boolean isWatermarkCreated(final Tuple lastTuple, final Tuple tuple) { if(lastTuple == null) { return false; } if(tupleBuilder instanceof ADSBTupleBuilder2D || tupleBuilder instanceof ADSBTupleBuilder3D) { final GeoJsonPolygon polygonOld = GeoJsonPolygon.fromGeoJson(new String(tuple.getDataBytes())); final GeoJsonPolygon polygonNew = GeoJsonPolygon.fromGeoJson(new String(tuple.getDataBytes())); return (polygonOld.getId() > polygonNew.getId()); } if(tupleBuilder instanceof BerlinModTupleBuilder) { final long newTimestamp = tuple.getVersionTimestamp(); if(lastWatermarkGenerated == 0) { lastWatermarkGenerated = newTimestamp; return false; } if(lastWatermarkGenerated + 60 < newTimestamp) { lastWatermarkGenerated = newTimestamp; return true; } return false; } if(tupleBuilder instanceof GeoJSONTupleBuilder) { final GeoJsonPolygon polygonNew = GeoJsonPolygon.fromGeoJson(new String(tuple.getDataBytes())); final String newTimestampString = polygonNew.getProperties().getOrDefault("TimestampParsed", "-1"); final long newTimestamp = MathUtil.tryParseLongOrExit(newTimestampString, () -> "Unable to parse: " + newTimestampString); if(lastWatermarkGenerated == 0) { lastWatermarkGenerated = newTimestamp; return false; } if(lastWatermarkGenerated + 60 < newTimestamp) { lastWatermarkGenerated = newTimestamp; return true; } return false; } System.out.println("Unsupported tuple builder: " + tupleBuilder); System.exit(1); return false; } /** * Determine the size of the distribution state * @return */ private long determineStateSize() { long size = 0; for(Map.Entry<String, Long> entry : distributionState.entrySet()) { size = size + entry.getKey().getBytes().length; size = size + 8; } return size; } /** * Determine the lines of the file * @return * @throws IOException */ private long determineLinesInInput() { final String filename = inputFile.getAbsolutePath(); try(FileLineIndex fli = new FileLineIndex(filename)) { System.out.format("Indexing %s%n", filename); fli.indexFile(); return fli.getIndexedLines(); } catch (IOException e) { e.printStackTrace(); System.exit(1); return -1; } } /*** * Main * Main * Main * Main * Main */ public static void main(final String[] args) { if(args.length != 2) { System.err.println("Usage: <Class> <Filename> <Format>"); System.exit(1); } final String filename = args[0]; final String format = args[1]; // Check file final File inputFile = new File(filename); if(! inputFile.isFile()) { System.err.println("Unable to open file: " + filename); System.exit(1); } final TupleBuilder tupleFactory = TupleBuilderFactory.getBuilderForFormat(format); final DetermineDistributionStateSize determineDistributionStateSize = new DetermineDistributionStateSize(inputFile, tupleFactory); determineDistributionStateSize.run(); } }
Minor fixes
bboxdb-experiments/src/main/java/org/bboxdb/experiments/DetermineDistributionStateSize.java
Minor fixes
Java
apache-2.0
91496d2f2958601d97d43999a7b73d9fa95b7eef
0
awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.hadoop.mapred.workflow.schedulers; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.ClusterStatus; import org.apache.hadoop.mapred.EagerTaskInitializationListener; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.JobInProgress; import org.apache.hadoop.mapred.JobStatus; import org.apache.hadoop.mapred.Task; import org.apache.hadoop.mapred.TaskScheduler; import org.apache.hadoop.mapred.TaskTrackerStatus; import org.apache.hadoop.mapred.workflow.WorkflowConf; import org.apache.hadoop.mapred.workflow.WorkflowInProgress; import org.apache.hadoop.mapred.workflow.scheduling.WorkflowListener; import org.apache.hadoop.mapred.workflow.scheduling.WorkflowScheduler; import org.apache.hadoop.mapred.workflow.scheduling.WorkflowSchedulingPlan; import org.apache.hadoop.mapred.workflow.scheduling.WorkflowSchedulingProtocol; import org.apache.hadoop.mapreduce.server.jobtracker.TaskTracker; import org.apache.hadoop.util.RunJar; public class WorkflowTaskScheduler extends TaskScheduler implements WorkflowScheduler { private static final Log LOG = LogFactory.getLog(WorkflowTaskScheduler.class); private WorkflowListener workflowListener; private EagerTaskInitializationListener eagerTaskInitializationListener; private WorkflowSchedulingProtocol workflowSchedulingProtocol; private WorkflowSchedulingPlan schedulingPlan; public WorkflowTaskScheduler() { workflowListener = new WorkflowListener(); } @Override public synchronized void start() throws IOException { super.start(); taskTrackerManager.addJobInProgressListener(workflowListener); taskTrackerManager.addWorkflowInProgressListener(workflowListener); eagerTaskInitializationListener.setTaskTrackerManager(taskTrackerManager); eagerTaskInitializationListener.start(); taskTrackerManager.addJobInProgressListener(eagerTaskInitializationListener); } @Override public synchronized void terminate() throws IOException { if (workflowListener != null) { taskTrackerManager.removeJobInProgressListener(workflowListener); taskTrackerManager.removeWorkflowInProgressListener(workflowListener); } if (eagerTaskInitializationListener != null) { taskTrackerManager.removeJobInProgressListener(eagerTaskInitializationListener); eagerTaskInitializationListener.terminate(); } super.terminate(); } @Override public synchronized void setConf(Configuration conf) { super.setConf(conf); eagerTaskInitializationListener = new EagerTaskInitializationListener(conf); } @Override public synchronized void setWorkflowSchedulingProtocol( WorkflowSchedulingProtocol workflowSchedulingProtocol) { this.workflowSchedulingProtocol = workflowSchedulingProtocol; } @Override // Called from JobTracker heartbeat function, which is called by a taskTracker public synchronized List<Task> assignTasks(TaskTracker taskTracker) throws IOException { if (taskTrackerManager.isInSafeMode()) { LOG.info("JobTracker is in safe mode, not scheduling any tasks."); return null; } if (schedulingPlan == null) { schedulingPlan = workflowSchedulingProtocol.getWorkflowSchedulingPlan(); if (schedulingPlan == null) { return null; } } // Find out what the next job/workflow to be executed is. Collection<Object> queue = workflowListener.getQueue(); List<Task> assignedTasks = new ArrayList<Task>(); synchronized (queue) { for (Object object : queue) { if (object instanceof JobInProgress) { // At this point we can execute tasks from any job we get, as the jobs // must have been added by the workflowInPorgress object in the queue. JobInProgress job = (JobInProgress) object; LOG.info("Got job from queue."); if (job.getStatus().getRunState() != JobStatus.RUNNING) { continue; } LOG.info("Job is in running state."); // A mapping between available machines (names) and machine types. Map<String, String> trackerMap = schedulingPlan.getTrackerMapping(); LOG.info("Got tracker mapping."); // Find out which tasktracker wants a task, and it's machine type. String tracker = taskTracker.getTrackerName(); String machineType = trackerMap.get(tracker); LOG.info("Got tracker: " + tracker + ", machineType: " + machineType); // Get cluster status information to see if there are free slots. ClusterStatus clusterStatus = taskTrackerManager.getClusterStatus(); TaskTrackerStatus tts = taskTracker.getStatus(); final int clusterSize = clusterStatus.getTaskTrackers(); final int uniqueHosts = taskTrackerManager.getNumberOfUniqueHosts(); LOG.info("Got cluster status info to compute tracker capacity."); String jobName = job.getJobConf().getJobName(); LOG.info("Checking if a map task can be run."); // Check if any slots are available on the tracker. final int mapCapacity = tts.getMaxMapSlots(); final int runningMaps = tts.countMapTasks(); final int availableMapSlots = mapCapacity - runningMaps; // TODO: what happens if task isn't null but sched. returns false? // If schedulingPlan.match() is true then we HAVE to schedule. if (availableMapSlots > 0) { Task task = job.obtainNewNodeLocalMapTask(tts, clusterSize, uniqueHosts); if (task != null && schedulingPlan.matchMap(machineType, jobName)) { assignedTasks.add(task); LOG.info("Assigning map task " + task.toString() + "."); } } LOG.info("Checking if a reduce task can be run."); // Check if any slots are available on the tracker. final int reduceCapacity = tts.getMaxReduceSlots(); final int runningReduces = tts.countReduceTasks(); final int availableReduceSlots = reduceCapacity - runningReduces; // TODO: what happens if task isn't null but sched. returns false? // If schedulingPlan.match() is true then we HAVE to schedule. if (availableReduceSlots > 0) { Task task = job.obtainNewReduceTask(tts, clusterSize, uniqueHosts); if (task != null && schedulingPlan.matchReduce(machineType, jobName)) { assignedTasks.add(task); LOG.info("Assigning reduce task " + task.toString() + "."); } } } else if (object instanceof WorkflowInProgress) { WorkflowInProgress workflow = (WorkflowInProgress) object; LOG.info("Got workflow from queue."); Collection<String> finishedJobs = workflow.getStatus().getFinishedJobs(); Collection<String> jobNames = schedulingPlan.getExecutableJobs(finishedJobs); LOG.info("Passed in finished jobs: " + finishedJobs); LOG.info("Got back executable jobs: " + jobNames); if (jobNames == null || jobNames.size() == 0) { LOG.info("All workflow jobs have been started."); continue; } for (String jobName : jobNames) { // Skip the job if it has already been started. if (!workflow.getStatus().getPrepJobs().contains(jobName)) { LOG.info("Skipping " + jobName + ", it has already been started."); continue; } JobConf jobConf = workflow.getConf().getJobs().get(jobName); // Check the jar for a manifest & add required attributes. updateJarManifest(workflow.getConf(), jobConf); // Submit the job. LOG.info("Submitting workflow job: " + jobConf.getJar()); workflow.getStatus().addSubmittedJob(jobConf.getJobName()); submitWorkflowJob(jobConf); } } } } return assignedTasks; } private void submitWorkflowJob(final JobConf jobConf) { new Thread(new Runnable() { public void run() { try { String[] args = { jobConf.getJar() }; RunJar.main(args); } catch (Throwable e) { e.printStackTrace(); } } }).start(); } // Check that the jar file has a manifest, and if not then add one. // Write configuration properties to the jar file's manifest. private void updateJarManifest(WorkflowConf workflowConf, JobConf jobConf) throws IOException { LOG.info("In updateJarManifest."); FileSystem fileSystem = FileSystem.get(workflowConf); Path filePath = new Path(jobConf.getJar()); Path newJarFile = new Path(filePath.toString() + ".tmp"); // Read/create the manifest. JarInputStream jarInput = new JarInputStream(fileSystem.open(filePath)); Manifest manifest = jarInput.getManifest(); LOG.info("Jar file is located at: " + filePath.toString()); if (manifest == null) { LOG.info("Manifest is null."); manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); } Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Main-Class", jobConf.getMainClass()); attributes.putValue("Arguments", jobConf.getArguments()); attributes.putValue("Input-Directory", jobConf.getInputDir()); attributes.putValue("Output-Directory", jobConf.getOutputDir()); attributes.putValue("Workflow-Id", jobConf.getWorkflowId()); attributes.putValue("Job-Id", jobConf.getJobId()); attributes.putValue("Job-Name", jobConf.getJobName()); LOG.info("Added manifest attributes."); // Write the new jar file. FSDataOutputStream out = fileSystem.create(newJarFile); JarOutputStream jarOutput = new JarOutputStream(out, manifest); JarEntry entry; int bytesRead; byte[] buffer = new byte[1024]; LOG.info("Writing new jar " + jarOutput.toString()); while ((entry = jarInput.getNextJarEntry()) != null) { jarOutput.putNextEntry(entry); while ((bytesRead = jarInput.read(buffer)) != -1) { jarOutput.write(buffer, 0, bytesRead); } } jarOutput.close(); jarInput.close(); LOG.info("Created new jar."); // Remove the old jar & rename the new one. fileSystem.delete(filePath, true); fileSystem.rename(newJarFile, filePath); LOG.info("Deleted old jar & renamed new one."); } @Override public synchronized Collection<JobInProgress> getJobs(String ignored) { // Both JobInProgress and WorkflowInProgress objects exist in the default // queue. Filter the queue to a Collection of JobInProgress objects. Collection<Object> queue = workflowListener.getQueue(); Collection<JobInProgress> jobQueue = new ArrayList<JobInProgress>(); for (Object object : queue) { if (object instanceof JobInProgress) { jobQueue.add((JobInProgress) object); } } return jobQueue; } }
src/mapred/org/apache/hadoop/mapred/workflow/schedulers/WorkflowTaskScheduler.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.hadoop.mapred.workflow.schedulers; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.ClusterStatus; import org.apache.hadoop.mapred.EagerTaskInitializationListener; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.JobInProgress; import org.apache.hadoop.mapred.JobStatus; import org.apache.hadoop.mapred.Task; import org.apache.hadoop.mapred.TaskScheduler; import org.apache.hadoop.mapred.TaskTrackerStatus; import org.apache.hadoop.mapred.workflow.WorkflowConf; import org.apache.hadoop.mapred.workflow.WorkflowInProgress; import org.apache.hadoop.mapred.workflow.scheduling.WorkflowListener; import org.apache.hadoop.mapred.workflow.scheduling.WorkflowScheduler; import org.apache.hadoop.mapred.workflow.scheduling.WorkflowSchedulingPlan; import org.apache.hadoop.mapred.workflow.scheduling.WorkflowSchedulingProtocol; import org.apache.hadoop.mapreduce.server.jobtracker.TaskTracker; import org.apache.hadoop.util.RunJar; public class WorkflowTaskScheduler extends TaskScheduler implements WorkflowScheduler { private static final Log LOG = LogFactory.getLog(WorkflowTaskScheduler.class); private WorkflowListener workflowListener; private EagerTaskInitializationListener eagerTaskInitializationListener; private WorkflowSchedulingProtocol workflowSchedulingProtocol; private WorkflowSchedulingPlan schedulingPlan; public WorkflowTaskScheduler() { workflowListener = new WorkflowListener(); } @Override public synchronized void start() throws IOException { super.start(); taskTrackerManager.addJobInProgressListener(workflowListener); taskTrackerManager.addWorkflowInProgressListener(workflowListener); eagerTaskInitializationListener.setTaskTrackerManager(taskTrackerManager); eagerTaskInitializationListener.start(); taskTrackerManager.addJobInProgressListener(eagerTaskInitializationListener); } @Override public synchronized void terminate() throws IOException { if (workflowListener != null) { taskTrackerManager.removeJobInProgressListener(workflowListener); taskTrackerManager.removeWorkflowInProgressListener(workflowListener); } if (eagerTaskInitializationListener != null) { taskTrackerManager.removeJobInProgressListener(eagerTaskInitializationListener); eagerTaskInitializationListener.terminate(); } super.terminate(); } @Override public synchronized void setConf(Configuration conf) { super.setConf(conf); eagerTaskInitializationListener = new EagerTaskInitializationListener(conf); } @Override public synchronized void setWorkflowSchedulingProtocol( WorkflowSchedulingProtocol workflowSchedulingProtocol) { this.workflowSchedulingProtocol = workflowSchedulingProtocol; } @Override // Called from JobTracker heartbeat function, which is called by a taskTracker public synchronized List<Task> assignTasks(TaskTracker taskTracker) throws IOException { if (taskTrackerManager.isInSafeMode()) { LOG.info("JobTracker is in safe mode, not scheduling any tasks."); return null; } if (schedulingPlan == null) { schedulingPlan = workflowSchedulingProtocol.getWorkflowSchedulingPlan(); if (schedulingPlan == null) { return null; } } // Find out what the next job/workflow to be executed is. Collection<Object> queue = workflowListener.getQueue(); List<Task> assignedTasks = new ArrayList<Task>(); synchronized (queue) { for (Object object : queue) { if (object instanceof JobInProgress) { // At this point we can execute tasks from any job we get, as the jobs // must have been added by the workflowInPorgress object in the queue. JobInProgress job = (JobInProgress) object; LOG.info("Got job from queue."); if (job.getStatus().getRunState() != JobStatus.RUNNING) { LOG.info("Job is not in running state, continuing."); continue; } // A mapping between available machines (names) and machine types. Map<String, String> trackerMap = schedulingPlan.getTrackerMapping(); LOG.info("Got tracker mapping."); // Find out which tasktracker wants a task, and it's machine type. String tracker = taskTracker.getTrackerName(); String machineType = trackerMap.get(tracker); LOG.info("Got tracker: " + tracker + ", machineType: " + machineType); // Match the job with an available task. // -If a running job exists for machine type, run next job/task on it. // -It is up to the schedulingPlan to decide what to do if there // doesn't exist any machines of the required type. String jobName = job.getJobConf().getJobName(); boolean runMap = schedulingPlan.matchMap(machineType, jobName); boolean runReduce = schedulingPlan.matchReduce(machineType, jobName); LOG.info("Job " + jobName + " is running:" + (runMap ? " map " : "") + (runReduce ? " reduce " : "") + "tasks."); // Run a task from the job on the given tracker. if (runMap || runReduce) { Task task; ClusterStatus clusterStatus = taskTrackerManager.getClusterStatus(); TaskTrackerStatus tts = taskTracker.getStatus(); final int clusterSize = clusterStatus.getTaskTrackers(); final int uniqueHosts = taskTrackerManager.getNumberOfUniqueHosts(); LOG.info("Got cluster status info to compute tracker capacity."); if (runMap) { LOG.info("Checking if a map task can be run."); // Check if any slots are available on the tracker. final int mapCapacity = tts.getMaxMapSlots(); final int runningMaps = tts.countMapTasks(); final int availableMapSlots = mapCapacity - runningMaps; // Attempt to assign map tasks. // TODO: all or just one? for (int i = 0; i < availableMapSlots; i++) { task = job.obtainNewMapTask(tts, clusterSize, uniqueHosts); if (task != null) { assignedTasks.add(task); LOG.info("Assigning map task " + task.toString() + "."); // TODO: update schedulingPlan that task was run } } } // Don't run a reduce task if there aren't supposed to be any // TODO if (runReduce) { LOG.info("Checking if a reduce task can be run."); // Check if any slots are available on the tracker. final int reduceCapacity = tts.getMaxReduceSlots(); final int runningReduces = tts.countReduceTasks(); final int availableReduceSlots = reduceCapacity - runningReduces; // Attempt to assign reduce tasks. for (int i = 0; i < availableReduceSlots; i++) { task = job.obtainNewReduceTask(tts, clusterSize, uniqueHosts); if (task != null) { assignedTasks.add(task); LOG.info("Assigning reduce task " + task.toString() + "."); // TODO: update schedulingPlan that task was run } } } } } else if (object instanceof WorkflowInProgress) { WorkflowInProgress workflow = (WorkflowInProgress) object; LOG.info("Got workflow from queue."); Collection<String> finishedJobs = workflow.getStatus().getFinishedJobs(); Collection<String> jobNames = schedulingPlan.getExecutableJobs(finishedJobs); LOG.info("Passed in finished jobs: " + finishedJobs); LOG.info("Got back executable jobs: " + jobNames); if (jobNames == null || jobNames.size() == 0) { LOG.info("All workflow jobs have been started."); continue; } for (String jobName : jobNames) { // Skip the job if it has already been started. if (!workflow.getStatus().getPrepJobs().contains(jobName)) { LOG.info("Skipping " + jobName + ", it has already been started."); continue; } JobConf jobConf = workflow.getConf().getJobs().get(jobName); // Check the jar for a manifest & add required attributes. updateJarManifest(workflow.getConf(), jobConf); // Submit the job. LOG.info("Submitting workflow job: " + jobConf.getJar()); workflow.getStatus().addSubmittedJob(jobConf.getJobName()); submitWorkflowJob(jobConf); } } } } return assignedTasks; } private void submitWorkflowJob(final JobConf jobConf) { new Thread(new Runnable() { public void run() { try { String[] args = { jobConf.getJar() }; RunJar.main(args); } catch (Throwable e) { e.printStackTrace(); } } }).start(); } // Check that the jar file has a manifest, and if not then add one. // Write configuration properties to the jar file's manifest. private void updateJarManifest(WorkflowConf workflowConf, JobConf jobConf) throws IOException { LOG.info("In updateJarManifest."); FileSystem fileSystem = FileSystem.get(workflowConf); Path filePath = new Path(jobConf.getJar()); Path newJarFile = new Path(filePath.toString() + ".tmp"); // Read/create the manifest. JarInputStream jarInput = new JarInputStream(fileSystem.open(filePath)); Manifest manifest = jarInput.getManifest(); LOG.info("Jar file is located at: " + filePath.toString()); if (manifest == null) { LOG.info("Manifest is null."); manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); } Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Main-Class", jobConf.getMainClass()); attributes.putValue("Arguments", jobConf.getArguments()); attributes.putValue("Input-Directory", jobConf.getInputDir()); attributes.putValue("Output-Directory", jobConf.getOutputDir()); attributes.putValue("Workflow-Id", jobConf.getWorkflowId()); attributes.putValue("Job-Id", jobConf.getJobId()); attributes.putValue("Job-Name", jobConf.getJobName()); LOG.info("Added manifest attributes."); // Write the new jar file. FSDataOutputStream out = fileSystem.create(newJarFile); JarOutputStream jarOutput = new JarOutputStream(out, manifest); JarEntry entry; int bytesRead; byte[] buffer = new byte[1024]; LOG.info("Writing new jar " + jarOutput.toString()); while ((entry = jarInput.getNextJarEntry()) != null) { jarOutput.putNextEntry(entry); while ((bytesRead = jarInput.read(buffer)) != -1) { jarOutput.write(buffer, 0, bytesRead); } } jarOutput.close(); jarInput.close(); LOG.info("Created new jar."); // Remove the old jar & rename the new one. fileSystem.delete(filePath, true); fileSystem.rename(newJarFile, filePath); LOG.info("Deleted old jar & renamed new one."); } @Override public synchronized Collection<JobInProgress> getJobs(String ignored) { // Both JobInProgress and WorkflowInProgress objects exist in the default // queue. Filter the queue to a Collection of JobInProgress objects. Collection<Object> queue = workflowListener.getQueue(); Collection<JobInProgress> jobQueue = new ArrayList<JobInProgress>(); for (Object object : queue) { if (object instanceof JobInProgress) { jobQueue.add((JobInProgress) object); } } return jobQueue; } }
Updated workflow scheduler.
src/mapred/org/apache/hadoop/mapred/workflow/schedulers/WorkflowTaskScheduler.java
Updated workflow scheduler.
Java
apache-2.0
29c400458fda57f05b2a990c0de20a5ec081b257
0
CloudSlang/cloud-slang,natabeck/cloud-slang,narry/cloud-slang,CloudSlang/cloud-slang,jrosadohp/cloud-slang,shajyhia/score-language,shajyhia/score-language,CloudSlang/cloud-slang,natabeck/cloud-slang,CloudSlang/cloud-slang,jrosadohp/cloud-slang,narry/cloud-slang
package com.hp.score.lang.tests.runtime.bindings; /* * Licensed to Hewlett-Packard Development Company, L.P. under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.hp.score.lang.entities.bindings.Input; import com.hp.score.lang.runtime.bindings.InputsBinding; import com.hp.score.lang.runtime.bindings.ScriptEvaluator; import com.hp.score.lang.runtime.configuration.SlangRuntimeSpringConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.python.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class InputsBindingTest { @Autowired private InputsBinding inputsBinding; @Test public void testEmptyBindInputs() throws Exception { List<Input> inputs = Lists.newArrayList(); Map<String,Serializable> result = inputsBinding.bindInputs(new HashMap<String,Serializable>(),inputs); Assert.assertTrue(result.isEmpty()); } @Test public void testDefaultValue() throws Exception { List<Input> inputs = Lists.newArrayList(createDefaultValueInput("value")); Map<String,Serializable> result = inputsBinding.bindInputs(new HashMap<String,Serializable>(),inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals("value", result.get("input1")); } @Test public void testDefaultValueInt() throws Exception { List<Input> inputs = Lists.newArrayList(createDefaultValueInput(2)); Map<String,Serializable> result = inputsBinding.bindInputs(new HashMap<String,Serializable>(),inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals(2, result.get("input1")); } @Test public void testTwoInputs() throws Exception { List<Input> inputs = Lists.newArrayList(new Input("input2",null,"yyy",false,false),createDefaultValueInput("zzz")); Map<String,Serializable> result = inputsBinding.bindInputs(new HashMap<String,Serializable>(),inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals("zzz", result.get("input1")); Assert.assertTrue(result.containsKey("input2")); Assert.assertEquals("yyy", result.get("input2")); } @Test public void testInputRef() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("inputX","xxx"); List<Input> inputs = Lists.newArrayList(new Input("input1","inputX")); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals("xxx", result.get("input1")); } @Test public void testInputScriptEval() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("valX",5); Input scriptInput = new Input("input1","3 + valX"); List<Input> inputs = Lists.newArrayList(scriptInput); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals(8, result.get("input1")); } @Test public void testInputScriptEval2() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("valB","b"); context.put("valC","c"); Input scriptInput = new Input("input1"," 'a' + valB + valC"); List<Input> inputs = Lists.newArrayList(scriptInput); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals("abc", result.get("input1")); } @Test public void testDefaultValueVsEmptyRef() throws Exception { Map<String,Serializable> context = new HashMap<>(); Input refInput = new Input("input1","NotExistent","val",false,false); List<Input> inputs = Lists.newArrayList(refInput); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals("val", result.get("input1")); } @Test public void testAssignFromAndExpr() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("input1",3); Input input = new Input("input1","5+7",null,false,false); List<Input> inputs = Lists.newArrayList(input); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals(3, result.get("input1")); } @Test public void testAssignFromAndConst() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("input1",3); Input input = new Input("input1",null,5,false,false); List<Input> inputs = Lists.newArrayList(input); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals(3, result.get("input1")); } @Test public void testComplexExpr() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("input1",3); Input input = new Input("input2"," input1 + 3 * 2 ",null,false,false); List<Input> inputs = Lists.newArrayList(input); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input2")); Assert.assertEquals(9, result.get("input2")); Assert.assertEquals(1, result.size()); } @Test public void testAssignFromVsRef() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("input2",3); context.put("input1",5); Input input = new Input("input1","input2",null,false,false); List<Input> inputs = Lists.newArrayList(input); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals(5, result.get("input1")); Assert.assertEquals(1, result.size()); } private Input createDefaultValueInput(Serializable value){ return new Input("input1",null,value,false,false); } @Configuration @Import(SlangRuntimeSpringConfig.class) static class Config{ @Bean public InputsBinding inputsBinding(){ return new InputsBinding(); } @Bean public ScriptEvaluator scriptEvaluator(){ return new ScriptEvaluator(); } } }
score-lang-runtime/src/test/java/com/hp/score/lang/tests/runtime/bindings/InputsBindingTest.java
package com.hp.score.lang.tests.runtime.bindings; /* * Licensed to Hewlett-Packard Development Company, L.P. under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.hp.score.lang.entities.bindings.Input; import com.hp.score.lang.runtime.bindings.InputsBinding; import com.hp.score.lang.runtime.bindings.ScriptEvaluator; import com.hp.score.lang.runtime.configuration.SlangRuntimeSpringConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.python.google.common.collect.Lists; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class InputsBindingTest { @Autowired private InputsBinding inputsBinding; @Test public void testEmptyBindInputs() throws Exception { List<Input> inputs = Lists.newArrayList(); Map<String,Serializable> result = inputsBinding.bindInputs(new HashMap<String,Serializable>(),inputs); Assert.assertTrue(result.isEmpty()); } @Test public void testDefaultValue() throws Exception { List<Input> inputs = Lists.newArrayList(createDefaultValueInput("value")); Map<String,Serializable> result = inputsBinding.bindInputs(new HashMap<String,Serializable>(),inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals("value", result.get("input1")); } @Test public void testDefaultValueInt() throws Exception { List<Input> inputs = Lists.newArrayList(createDefaultValueInput(2)); Map<String,Serializable> result = inputsBinding.bindInputs(new HashMap<String,Serializable>(),inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals(2, result.get("input1")); } @Test public void testTwoInputs() throws Exception { List<Input> inputs = Lists.newArrayList(new Input("input2",null,"yyy",false,false),createDefaultValueInput("zzz")); Map<String,Serializable> result = inputsBinding.bindInputs(new HashMap<String,Serializable>(),inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals("zzz", result.get("input1")); Assert.assertTrue(result.containsKey("input2")); Assert.assertEquals("yyy", result.get("input2")); } @Test public void testInputRef() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("inputX","xxx"); List<Input> inputs = Lists.newArrayList(new Input("input1","inputX")); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals("xxx", result.get("input1")); } @Test public void testInputScriptEval() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("valX",5); Input scriptInput = new Input("input1","3 + valX"); List<Input> inputs = Lists.newArrayList(scriptInput); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals(8, result.get("input1")); } @Test public void testInputScriptEval2() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("valB","b"); context.put("valC","c"); Input scriptInput = new Input("input1"," 'a' + valB + valC"); List<Input> inputs = Lists.newArrayList(scriptInput); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals("abc", result.get("input1")); } @Test public void testDefaultValueVsEmptyRef() throws Exception { Map<String,Serializable> context = new HashMap<>(); Input refInput = new Input("input1","NotExistent","val",false,false); List<Input> inputs = Lists.newArrayList(refInput); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals("val", result.get("input1")); } @Test public void testAssignFromAndExpr() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("input1",3); Input input = new Input("input1","5+7",null,false,false); List<Input> inputs = Lists.newArrayList(input); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals(3, result.get("input1")); } @Test public void testAssignFromAndConst() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("input1",3); Input input = new Input("input1",null,5,false,false); List<Input> inputs = Lists.newArrayList(input); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input1")); Assert.assertEquals(3, result.get("input1")); } @Test public void testComplexExpr() throws Exception { Map<String,Serializable> context = new HashMap<>(); context.put("input1",3); Input input = new Input("input2"," input1 + 3 * 2 ",null,false,false); List<Input> inputs = Lists.newArrayList(input); Map<String,Serializable> result = inputsBinding.bindInputs(context,inputs); Assert.assertFalse(result.isEmpty()); Assert.assertTrue(result.containsKey("input2")); Assert.assertEquals(9, result.get("input2")); Assert.assertEquals(1, result.size()); } private Input createDefaultValueInput(Serializable value){ return new Input("input1",null,value,false,false); } @Configuration @Import(SlangRuntimeSpringConfig.class) static class Config{ @Bean public InputsBinding inputsBinding(){ return new InputsBinding(); } @Bean public ScriptEvaluator scriptEvaluator(){ return new ScriptEvaluator(); } } }
add tests to InputsBindingTest.
score-lang-runtime/src/test/java/com/hp/score/lang/tests/runtime/bindings/InputsBindingTest.java
add tests to InputsBindingTest.
Java
apache-2.0
cf4bef0beb065ead99498553cfde762fd407c48a
0
StraaS/StraaS-android-sdk-sample
package io.straas.android.media.demo.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.os.Bundle; import android.support.annotation.DrawableRes; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StyleRes; import android.support.graphics.drawable.VectorDrawableCompat; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.support.v4.media.MediaBrowserCompat.ConnectionCallback; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaControllerCompat; import android.support.v4.media.session.MediaSessionCompat.QueueItem; import android.support.v4.media.session.PlaybackStateCompat; import android.support.v4.util.SparseArrayCompat; import android.support.v4.view.GestureDetectorCompat; import android.support.v4.widget.TextViewCompat; import android.support.v7.widget.AppCompatImageButton; import android.support.v7.widget.AppCompatImageView; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.google.android.exoplayer2.Format; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import io.straas.android.media.demo.MediaControllerCompatHelper; import io.straas.android.media.demo.MediaControllerCompatHelper.VideoQualityInfo; import io.straas.android.media.demo.MediaControllerCompatHelper.VideoQualityInfoCallback; import io.straas.android.media.demo.Utils; import io.straas.android.media.demo.widget.ui.ContentSeekBar; import io.straas.android.media.demo.widget.ui.SwitchQualityDialog; import io.straas.android.media.demo.widget.ui.SwitchSpeedDialog; import io.straas.android.sdk.demo.R; import io.straas.android.sdk.media.StraasMediaCore; import io.straas.android.sdk.media.StraasMediaCore.ErrorReason; import io.straas.android.sdk.media.VideoCustomMetadata; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_DVR_PLAYBACK_AVAILABLE; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_ENDED; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_STARTED; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_STOPPED; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_UNKNOWN; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_WAITING_FOR_STREAM; import static io.straas.android.sdk.media.StraasMediaCore.KEY_EXTRA_TEXT_TRACKS; import static io.straas.android.sdk.media.StraasMediaCore.LIVE_EXTRA_BROADCAST_STATE_V2; public final class StraasPlayerView extends FrameLayout implements StraasMediaCore.UiContainer { private static final String TAG = StraasPlayerView.class.getSimpleName(); public static final int PLAYBACK_MODE_VOD = 0; public static final int PLAYBACK_MODE_LIVE_EDGE = 1; public static final int PLAYBACK_MODE_LIVE_DVR = 2; @IntDef({PLAYBACK_MODE_VOD, PLAYBACK_MODE_LIVE_EDGE, PLAYBACK_MODE_LIVE_DVR}) @Retention(RetentionPolicy.CLASS) public @interface PlaybackMode {} private static final int AUTO_HIDE_DELAY_MILLIS = 3000; private final Float[] PLAYBACK_SPEED_OPTIONS = {0.5f, 1.0f, 1.5f, 2.0f}; private boolean mEnableDefaultWidget; private boolean mEnableDefaultSwitchQualityIcon; private boolean mEnableDefaultSwitchQualityDialog; private boolean mEnableDefaultSwitchSpeedIcon; private boolean mEnableDefaultTextTrackToggle; private boolean mEnableDefaultChannelName; private boolean mEnableDefaultSummaryViewer; private boolean mEnableDefaultLoadingProgressBar; private boolean mEnableDefaultContentSeekBar; private boolean mEnableDefaultTextTrack; private boolean mEnableDefaultPlay; private boolean mEnableDefaultPause; private boolean mEnableDefaultReplay; private boolean mEnableDefaultPrevious; private boolean mEnableDefaultNext; private boolean mEnableDefaultErrorMessage; private boolean mEnableDefaultBroadcastStateMessage; private boolean mIsBind; private boolean mIsLive = false; private boolean mIsLiveSeekable; @PlaybackMode private int mPlaybackMode = PLAYBACK_MODE_VOD; private boolean mCanToggleControllerUi = false; private View mControllerContainer; private View mColumnPlayPause; private ViewGroup mColumnSummaryViewer; private ViewGroup mColumnChannelName; private ViewGroup mColumnContentSeekBar; private ViewGroup mColumnLoadingBar; private ViewGroup mColumnPlay; private ViewGroup mColumnPause; private ViewGroup mColumnReplay; private ViewGroup mColumnPrevious; private ViewGroup mColumnNext; private ViewGroup mColumnDvrPlaybackAvailable; private ViewGroup mColumnAdPlay; private ViewGroup mColumnErrorMessage; private ViewGroup mColumnBroadcastState; private ViewGroup mColumnTopRight; private ViewGroup mColumnTopRight2; private ViewGroup mColumnBottomLeft; private ViewGroup mColumnBottomRight1; private ViewGroup mColumnBottomRight2; private TextView mChannelNameTextView; private TextView mSummaryViewerTextView; private TextView mErrorMessageTextView; private TextView mLivePositionTimeTextView; private View mBroadcastStateView; private View mSwitchQualityView; private View mSwitchSpeedView; private View mTextTrackToggle; private View mLogoView; private ContentSeekBar mContentSeekBar; private TextView mTextTrackView; private View mDvrPlaybackAvailableView; private FrameLayout mVideoView; private FrameLayout mAdView; private ImageView imagePoster; private ViewGroup mTextTrack; private FragmentActivity mFragmentActivity; private Bundle mLiveBundle; private MediaMetadataCompat mLastMediaMetadata; private PlaybackStateCompat mLastPlaybackStateCompat; private StraasMediaCore mStraasMediaCore; private int mImageButtonBackground; private Context mThemeContext; private GestureDetectorCompat mGestureDetector, mGestureTapDetector, mGestureFakeDetector; private SwitchQualityViewClickListener mSwitchQualityViewListener; private ChannelNameMetadataListener mChannelNameMetadataListener = new ChannelNameMetadataListener(); private SummaryViewerMetadataListener mSummaryViewerMetadataListener = new SummaryViewerMetadataListener(); private ErrorMessageListener mErrorMessageListener = new ErrorMessageListener(); private LivePositionTimeListener mLivePositionTimeListener = new LivePositionTimeListener(); private BroadcastStateListener mBroadcastStateListener = new BroadcastStateListener(); private List<ConnectionCallback> mMediaConnectedListenerList = new ArrayList<>(); private SparseArrayCompat<ViewGroup> mCustomColumnList = new SparseArrayCompat<>(); private List<QueueItem> mLastQueueList; private int mUIBroadcastState = BROADCAST_STATE_UNKNOWN; public interface SwitchQualityViewClickListener { void onFormatCallback(ArrayList<Format> formats, int currentIndex); } public static final int CUSTOM_COLUMN_TOP_RIGHT = 0; public static final int CUSTOM_COLUMN_BOTTOM_LEFT = 1; public static final int CUSTOM_COLUMN_BOTTOM_RIGHT1 = 2; public static final int CUSTOM_COLUMN_BOTTOM_RIGHT2 = 3; public static final int CUSTOM_COLUMN_TOP_RIGHT2 = 4; @IntDef({CUSTOM_COLUMN_TOP_RIGHT, CUSTOM_COLUMN_BOTTOM_LEFT, CUSTOM_COLUMN_BOTTOM_RIGHT1, CUSTOM_COLUMN_BOTTOM_RIGHT2, CUSTOM_COLUMN_TOP_RIGHT2}) @Retention(RetentionPolicy.SOURCE) public @interface CustomColumnPosition { } public StraasPlayerView(Context context) { this(context, null); } public StraasPlayerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public StraasPlayerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StraasLayout, defStyleAttr, 0); getCustomizedAttr(typedArray); typedArray.recycle(); } /** * Initialize a StrassPlayerView, which can be used to generate layout and control UI. * * @param fragmentActivity A FragmentActivity which use StraasPlayerView. */ public void initialize(@NonNull FragmentActivity fragmentActivity) { initialize(fragmentActivity, null); } /** * Initialize a StrassPlayerView, which can be used to generate layout and control UI. * * @param fragmentActivity A FragmentActivity which use StraasPlayerView. * @param configuration A configuration for whether default widget to use or not. */ public void initialize(@NonNull FragmentActivity fragmentActivity, @Nullable StraasConfiguration configuration) { mFragmentActivity = fragmentActivity; if (configuration != null) { initConfiguration(configuration); } init(); } public Context getThemeContext() { return mThemeContext; } private void init() { ViewGroup straasMainContainer = (ViewGroup) LayoutInflater.from(getContext()) .inflate(R.layout.straas_main_container, this, false); mThemeContext = straasMainContainer.getContext(); int[] attr = new int[]{R.attr.selectableItemBackgroundBorderless}; TypedArray typedArray = mThemeContext.obtainStyledAttributes(attr); mImageButtonBackground = Build.VERSION.SDK_INT > 21 ? typedArray.getResourceId(0, 0) : 0; typedArray.recycle(); mControllerContainer = straasMainContainer.findViewById(R.id.controllerContainer); straasMainContainer.findViewById(R.id.upContainer).setBackground( new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[]{ContextCompat.getColor(mThemeContext, android.R.color.transparent), ContextCompat.getColor(mThemeContext, R.color.color_controller_background_dark)})); straasMainContainer.findViewById(R.id.bottomContainer).setBackground( new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{ContextCompat.getColor(mThemeContext, android.R.color.transparent), ContextCompat.getColor(mThemeContext, R.color.color_controller_background_dark)})); mVideoView = straasMainContainer.findViewById(R.id.videoSurfaceView); mTextTrack = straasMainContainer.findViewById(R.id.textTrack); imagePoster = new ImageView(getThemeContext()); initColumn(straasMainContainer); mGestureTapDetector = new GestureDetectorCompat(getContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent event) { if (!mCanToggleControllerUi) { return false; } Utils.toggleViewVisibilityWithAnimation(AUTO_HIDE_DELAY_MILLIS, mControllerContainer, mColumnPlayPause); return true; } @Override public boolean onDown(MotionEvent e) { return true; } }); mGestureFakeDetector = new GestureDetectorCompat(getContext(), new GestureDetector.SimpleOnGestureListener()); if (mEnableDefaultWidget) { if (mEnableDefaultSwitchQualityIcon) { View switchQualityView = View.inflate(mThemeContext, R.layout.switch_quality_layout, null); setSwitchQualityViewPosition(switchQualityView, CUSTOM_COLUMN_TOP_RIGHT); } if (mEnableDefaultSwitchSpeedIcon) { View switchQualityView = View.inflate(mThemeContext, R.layout.switch_speed_layout, null); setSwitchSpeedViewPosition(switchQualityView, CUSTOM_COLUMN_TOP_RIGHT2); } if (mEnableDefaultTextTrackToggle) { View textTrackToggleView = View.inflate(mThemeContext, R.layout.text_track_toggle, null); setTextTrackToggleViewPosition(textTrackToggleView, CUSTOM_COLUMN_BOTTOM_RIGHT2); } if (mEnableDefaultChannelName) { TextView channelNameTextView = (TextView) View.inflate(mThemeContext, R.layout.channel_name, null); setCustomChannelName(channelNameTextView); } if (mEnableDefaultSummaryViewer) { TextView summaryViewerTextView = (TextView) View.inflate(mThemeContext, R.layout.summary_viewer, null); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(summaryViewerTextView, VectorDrawableCompat.create(getResources(), R.drawable.ic_eye_24dp, null), null, null, null); setCustomSummaryViewerView(summaryViewerTextView); } if (mEnableDefaultLoadingProgressBar) { ProgressBar progressBar = (ProgressBar) View.inflate(mThemeContext, R.layout.loading_progress_bar, null); setCustomLoadingProgressBar(progressBar); } if (mEnableDefaultContentSeekBar) { ContentSeekBar contentSeekBar = new ContentSeekBar(mThemeContext); setCustomContentSeekBar(contentSeekBar); } if (mEnableDefaultTextTrack) { TextView textTrackView = (TextView) View.inflate(mThemeContext, R.layout.text_track, null); setCustomTextTrack(textTrackView); } if (mEnableDefaultPlay) { setCustomPlayIcon(R.drawable.ic_play_arrow_48dp); } if (mEnableDefaultPause) { setCustomPauseIcon(R.drawable.ic_pause_48dp); } if (mEnableDefaultReplay) { setCustomReplayIcon(R.drawable.ic_replay_48dp); } if (mEnableDefaultPrevious) { setCustomSkipToPreviousIcon(R.drawable.ic_skip_previous_48dp); } if (mEnableDefaultNext) { setCustomSkipToNextIcon(R.drawable.ic_skip_next_48px); } if (mEnableDefaultErrorMessage) { TextView errorMessageTextView = (TextView) View.inflate(mThemeContext, R.layout.error_message, null); Drawable drawable = VectorDrawableCompat.create(getResources(), R.drawable.ic_error_player, null); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(errorMessageTextView, drawable, null, null, null); setCustomErrorMessage(errorMessageTextView); } if (mEnableDefaultBroadcastStateMessage) { View broadcastStateOffline = View.inflate(mThemeContext, R.layout.broadcast_offline, null); setCustomBroadcastState(broadcastStateOffline); } } mAdView = straasMainContainer.findViewById(R.id.adSurfaceView); addView(straasMainContainer); setAutoHideControllerUiWhenTouch(true); } public void hideControllerViews() { mControllerContainer.setVisibility(GONE); mColumnPlayPause.setVisibility(GONE); mColumnAdPlay.setVisibility(GONE); mColumnLoadingBar.setVisibility(GONE); mColumnBroadcastState.setVisibility(GONE); mColumnErrorMessage.setVisibility(GONE); } private void initConfiguration(StraasConfiguration configuration) { mEnableDefaultWidget = configuration.isEnableDefaultWidget(); mEnableDefaultSwitchQualityIcon = configuration.isEnableDefaultSwitchQuality(); mEnableDefaultSwitchSpeedIcon = configuration.isEnableDefaultSwitchSpeed(); mEnableDefaultTextTrackToggle = configuration.isEnableDefaultTextTrackToggle(); mEnableDefaultChannelName = configuration.isEnableDefaultChannelName(); mEnableDefaultSummaryViewer = configuration.isEnableDefaultSummaryViewer(); mEnableDefaultLoadingProgressBar = configuration.isEnableDefaultLoadingProgressBar(); mEnableDefaultContentSeekBar = configuration.isEnableDefaultContentProgressBar(); mEnableDefaultTextTrack = configuration.isEnableDefaultTextTrack(); mEnableDefaultPlay = configuration.isEnableDefaultPlay(); mEnableDefaultPause = configuration.isEnableDefaultPause(); mEnableDefaultReplay = configuration.isEnableDefaultReplay(); mEnableDefaultPrevious = configuration.isEnableDefaultSkipToPrevious(); mEnableDefaultNext = configuration.isEnableDefaultSkipToNext(); mEnableDefaultErrorMessage = configuration.isEnableDefaultErrorMessage(); mEnableDefaultBroadcastStateMessage = configuration.isEnableDefaultBroadcastStateMessage(); } private final MediaControllerCompat.Callback mMediaControllerCallback = new MediaControllerCompat.Callback() { @Override public void onQueueChanged(List<QueueItem> queue) { mLastQueueList = queue; if (mLastQueueList == null) { mLastMediaMetadata = null; if (mColumnPrevious.getVisibility() != GONE) { mColumnPrevious.setVisibility(GONE); } if (mColumnNext.getVisibility() != GONE) { mColumnNext.setVisibility(GONE); } } } @Override public void onSessionDestroyed() { } @Override public void onMetadataChanged(MediaMetadataCompat metadata) { if (metadata == null || (mLastMediaMetadata != null && TextUtils.equals(metadata.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID), mLastMediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID)) && TextUtils.equals(metadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE), mLastMediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE)) && metadata.getBundle().getBoolean(VideoCustomMetadata.CUSTOM_METADATA_IS_LIVE_LOW_LATENCY_FIRST) == mLastMediaMetadata.getBundle().getBoolean(VideoCustomMetadata.CUSTOM_METADATA_IS_LIVE_LOW_LATENCY_FIRST))) { return; } mLastMediaMetadata = metadata; String mediaId = mLastMediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID); if (TextUtils.isEmpty(mediaId)) { return; } if (mediaId.startsWith(StraasMediaCore.LIVE_ID_PREFIX)) { boolean isLiveSeekable = metadata.getBundle().getBoolean(VideoCustomMetadata.LIVE_DVR_ENABLED) && !metadata.getBundle().getBoolean(VideoCustomMetadata.CUSTOM_METADATA_IS_LIVE_LOW_LATENCY_FIRST); switchMode(true, isLiveSeekable); Bundle liveBundle = (mLiveBundle != null) ? mLiveBundle : getMediaControllerCompat().getExtras(); if (isLiveSeekable) { setCustomDvrPlaybackAvailable(View.inflate(mThemeContext, R.layout.dvr_playback_available, null)); } handleMediaSessionExtra(liveBundle, true); } else { switchMode(false, false); } if (mLastQueueList != null) { if (mLastPlaybackStateCompat.getActiveQueueItemId() == 0) { if (mColumnPrevious.getVisibility() != GONE) { mColumnPrevious.setVisibility(GONE); } } else if (mColumnPrevious.getVisibility() != VISIBLE) { mColumnPrevious.setVisibility(VISIBLE); } if (mLastPlaybackStateCompat.getActiveQueueItemId() == mLastQueueList.size() - 1) { if (mColumnNext.getVisibility() != GONE) { mColumnNext.setVisibility(GONE); } } else if (mColumnNext.getVisibility() != VISIBLE) { mColumnNext.setVisibility(VISIBLE); } } String title = metadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE); long summaryViewer = metadata.getBundle().getLong(VideoCustomMetadata.PLAY_COUNT_SUM); mChannelNameMetadataListener.onMetaChanged(mChannelNameTextView, title); mSummaryViewerMetadataListener.onMetaChanged(mSummaryViewerTextView, summaryViewer); if (!isVideoContainerHasPoster()) { getVideoContainer().addView(imagePoster, getVideoContainer().getChildCount()); } if (metadata.getBundle().containsKey(StraasMediaCore.KEY_VIDEO_RENDER_TYPE) && metadata.getBundle().getInt(StraasMediaCore.KEY_VIDEO_RENDER_TYPE) == StraasMediaCore.VIDEO_RENDER_TYPE_NONE) { imagePoster.setVisibility(VISIBLE); Glide.with(getThemeContext()) .asBitmap() .load(metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI)) .into(imagePoster); } else { imagePoster.setVisibility(GONE); } } @Override public void onCaptioningEnabledChanged(boolean enabled) { super.onCaptioningEnabledChanged(enabled); if (mTextTrackToggle != null) { mTextTrackToggle.setActivated(enabled); } } @Override public void onPlaybackStateChanged(PlaybackStateCompat state) { if (state == null || (mLastPlaybackStateCompat != null && mLastPlaybackStateCompat.getState() == state.getState() && mLastPlaybackStateCompat.getActiveQueueItemId() == state.getActiveQueueItemId())) { return; } if (mLastPlaybackStateCompat == null && mTextTrackView != null) { MediaControllerCompatHelper.setCaptionEnable(getMediaControllerCompat(), true); } mLastPlaybackStateCompat = state; if (!TextUtils.isEmpty(state.getErrorMessage())) { @ErrorReason.ErrorReasonType String errorType = state.getErrorMessage().toString(); mErrorMessageListener.onError(mErrorMessageTextView, errorType); if (mIsLive) { Bundle liveBundle = (mLiveBundle != null) ? mLiveBundle : getMediaControllerCompat().getExtras(); handleMediaSessionExtra(liveBundle, true); } if (getKeepScreenOn()) { setKeepScreenOn(false); } return; } if (mColumnErrorMessage.getVisibility() != GONE) { setErrorMessageVisibility(GONE); } if (state.getState() == PlaybackStateCompat.STATE_PLAYING) { setErrorMessageVisibility(GONE); setBroadcastStateVisibility(GONE); if (mControllerContainer.getVisibility() != GONE) { Utils.toggleViewVisibilityWithAnimation(AUTO_HIDE_DELAY_MILLIS, mControllerContainer, mColumnPlayPause); } } int loadingProgressBarVisibility = GONE; if (state.getActiveQueueItemId() == StraasMediaCore.AD_PLAYBACK_ID) { if (mControllerContainer.getVisibility() != GONE) { mControllerContainer.setVisibility(GONE); } if (mColumnPlayPause.getVisibility() != GONE) { mColumnPlayPause.setVisibility(GONE); } switch (state.getState()) { case PlaybackStateCompat.STATE_BUFFERING: loadingProgressBarVisibility = VISIBLE; break; case PlaybackStateCompat.STATE_PLAYING: mColumnAdPlay.setVisibility(GONE); mCanToggleControllerUi = false; break; case PlaybackStateCompat.STATE_PAUSED: mColumnAdPlay.setVisibility(VISIBLE); break; case PlaybackStateCompat.STATE_STOPPED: // After AD playing ends, SDK player will seek the live streaming to // the real-time coverage of live automatically for all kinds of live: // normal live, low latency, and live-dvr if (mIsLive) { refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_EDGE); } break; } } else { if (mColumnAdPlay.getVisibility() != GONE) { mColumnAdPlay.setVisibility(GONE); } switch (state.getState()) { case PlaybackStateCompat.STATE_BUFFERING: loadingProgressBarVisibility = VISIBLE; mColumnPlay.setVisibility(GONE); mColumnPause.setVisibility(GONE); break; case PlaybackStateCompat.STATE_PLAYING: mCanToggleControllerUi = true; switchToPause(); if (!getKeepScreenOn()) { setKeepScreenOn(true); } break; case PlaybackStateCompat.STATE_PAUSED: if (mPlaybackMode == PLAYBACK_MODE_LIVE_EDGE) { refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_DVR); } mCanToggleControllerUi = false; showControllerUi(); showPlayUi(); if (getKeepScreenOn()) { setKeepScreenOn(false); } break; case PlaybackStateCompat.STATE_NONE: mCanToggleControllerUi = false; hideControllerViews(); refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_EDGE); if (getKeepScreenOn()) { setKeepScreenOn(false); } case PlaybackStateCompat.STATE_STOPPED: mCanToggleControllerUi = true; if (mIsLive) { Bundle liveBundle = (mLiveBundle != null) ? mLiveBundle : getMediaControllerCompat().getExtras(); handleMediaSessionExtra(liveBundle, true); } switchToReplay(); if (getKeepScreenOn()) { setKeepScreenOn(false); } break; } } setLoadingProgressBarVisible(loadingProgressBarVisibility == VISIBLE); } @Override public void onSessionEvent(String event, Bundle extras) { switch (event) { case StraasMediaCore.EVENT_MEDIA_BROWSER_SERVICE_ERROR: mErrorMessageListener.onError(mErrorMessageTextView, extras.getString(StraasMediaCore.KEY_MEDIA_BROWSER_ERROR_REASON)); break; } } @Override public void onExtrasChanged(Bundle extras) { handleTextTrackExtra(extras); mLiveBundle = extras; if (!mIsLive) { return; } boolean isStopPlay = mLastPlaybackStateCompat != null && (mLastPlaybackStateCompat.getState() == PlaybackStateCompat.STATE_STOPPED || mLastPlaybackStateCompat.getState() == PlaybackStateCompat.STATE_NONE || mLastPlaybackStateCompat.getState() == PlaybackStateCompat.STATE_ERROR); handleMediaSessionExtra(extras, isStopPlay); } private boolean isVideoContainerHasPoster() { return getVideoContainer().getChildAt(getVideoContainer().getChildCount() - 1) == imagePoster; } }; private void handleTextTrackExtra(Bundle extras) { if (mTextTrackView == null) { return; } if (extras.containsKey(KEY_EXTRA_TEXT_TRACKS) && getMediaControllerCompat().isCaptioningEnabled()) { ArrayList<CharSequence> texts = extras.getCharSequenceArrayList(KEY_EXTRA_TEXT_TRACKS); if (texts == null || texts.isEmpty()) { mTextTrackView.setVisibility(GONE); } else { SpannableStringBuilder builder = new SpannableStringBuilder(); for (CharSequence text : texts) { builder.append(text); if (texts.indexOf(text) != texts.size() - 1) { builder.append("\n"); } } mTextTrackView.setVisibility(VISIBLE); mTextTrackView.setText(builder.toString()); } } else { mTextTrackView.setVisibility(GONE); } } private void handleMediaSessionExtra(Bundle extras, boolean shouldShowStateUi) { int broadcastStateV2 = extras.getInt(LIVE_EXTRA_BROADCAST_STATE_V2, BROADCAST_STATE_UNKNOWN); if (broadcastStateV2 != BROADCAST_STATE_STARTED && !shouldShowStateUi) { return; } if (broadcastStateV2 == mUIBroadcastState) { return; } mUIBroadcastState = broadcastStateV2; switch (broadcastStateV2) { case BROADCAST_STATE_STARTED: mBroadcastStateListener.online(); break; case BROADCAST_STATE_WAITING_FOR_STREAM: mBroadcastStateListener.waitForStream(mBroadcastStateView); break; case BROADCAST_STATE_DVR_PLAYBACK_AVAILABLE: mBroadcastStateListener.dvrPlaybackAvailable(mDvrPlaybackAvailableView); break; case BROADCAST_STATE_STOPPED: mBroadcastStateListener.offline(mBroadcastStateView); break; case BROADCAST_STATE_ENDED: mBroadcastStateListener.endEvent(mBroadcastStateView); break; } } /** * To set a channel name metadata change event. If channel name metadata is changed, it will trigger this listener * * @param listener A listener to listen channel name metadata changed event. */ public void setChannelNameMetalistener(@NonNull ChannelNameMetadataListener listener) { mChannelNameMetadataListener = listener; } /** * To set a summary viewer metadata change event. If summary viewer metadata is changed, it will trigger this listener * * @param listener A listener to listen summary viewer metadata changed event. */ public void setSummaryViewerMetadataListener(@NonNull SummaryViewerMetadataListener listener) { mSummaryViewerMetadataListener = listener; } private void getCustomizedAttr(TypedArray typedArray) { mEnableDefaultWidget = typedArray.getBoolean(R.styleable.StraasLayout_defaultWidget, true); mEnableDefaultSwitchQualityIcon = typedArray.getBoolean(R.styleable.StraasLayout_defaultSwitchQualityIcon, true); mEnableDefaultSwitchQualityDialog = typedArray.getBoolean(R.styleable.StraasLayout_defaultSwitchQualityDialog, true); mEnableDefaultSwitchSpeedIcon = typedArray.getBoolean(R.styleable.StraasLayout_defaultSwitchSpeedIcon, true); mEnableDefaultTextTrackToggle = typedArray.getBoolean(R.styleable.StraasLayout_defaultSwitchSpeedIcon, true); mEnableDefaultChannelName = typedArray.getBoolean(R.styleable.StraasLayout_defaultChannelName, true); mEnableDefaultSummaryViewer = typedArray.getBoolean(R.styleable.StraasLayout_defaultSummaryViewer, true); mEnableDefaultLoadingProgressBar = typedArray.getBoolean(R.styleable.StraasLayout_defaultLoadingProgressBar, true); mEnableDefaultContentSeekBar = typedArray.getBoolean(R.styleable.StraasLayout_defaultContentSeekbar, true); mEnableDefaultTextTrack = typedArray.getBoolean(R.styleable.StraasLayout_defaultTextTrack, true); mEnableDefaultPlay = typedArray.getBoolean(R.styleable.StraasLayout_defaultPlay, true); mEnableDefaultPause = typedArray.getBoolean(R.styleable.StraasLayout_defaultPause, true); mEnableDefaultReplay = typedArray.getBoolean(R.styleable.StraasLayout_defaultReplay, true); mEnableDefaultPrevious = typedArray.getBoolean(R.styleable.StraasLayout_defaultSkipToPrevious, true); mEnableDefaultNext = typedArray.getBoolean(R.styleable.StraasLayout_defaultSkipToNext, true); mEnableDefaultErrorMessage = typedArray.getBoolean(R.styleable.StraasLayout_defaultErrorMessage, true); mEnableDefaultBroadcastStateMessage = typedArray.getBoolean(R.styleable.StraasLayout_defaultBroadcastStateMessage, true); } private void initColumn(View root) { mColumnSummaryViewer = root.findViewById(R.id.summaryViewerColumn); mColumnChannelName = root.findViewById(R.id.channelNameColumn); mColumnLoadingBar = root.findViewById(R.id.loadingBarProgressColumn); mColumnContentSeekBar = root.findViewById(R.id.contentProgressBarColumn); mColumnPlay = root.findViewById(R.id.playColumn); mColumnPause = root.findViewById(R.id.pauseColumn); mColumnReplay = root.findViewById(R.id.replayColumn); mColumnPrevious = root.findViewById(R.id.previousColumn); mColumnNext = root.findViewById(R.id.nextColumn); mColumnPlayPause = root.findViewById(R.id.playPauseColumn); mColumnDvrPlaybackAvailable = root.findViewById(R.id.dvrPlaybackAvailableColumn); mColumnAdPlay = root.findViewById(R.id.adPlayColumn); mColumnErrorMessage = root.findViewById(R.id.errorMessageColumn); mColumnBroadcastState = root.findViewById(R.id.onLineOfflineColumn); mColumnTopRight = root.findViewById(R.id.customColumnTopRight); mColumnTopRight2 = root.findViewById(R.id.customColumnTopRight2); mColumnBottomLeft = root.findViewById(R.id.bottomLeftColumn); mColumnBottomRight1 = root.findViewById(R.id.bottomRightColumn1); mColumnBottomRight2 = root.findViewById(R.id.bottomRightColumn2); mCustomColumnList.put(CUSTOM_COLUMN_TOP_RIGHT, mColumnTopRight); mCustomColumnList.put(CUSTOM_COLUMN_TOP_RIGHT2, mColumnTopRight2); mCustomColumnList.put(CUSTOM_COLUMN_BOTTOM_LEFT, mColumnBottomLeft); mCustomColumnList.put(CUSTOM_COLUMN_BOTTOM_RIGHT1, mColumnBottomRight1); mCustomColumnList.put(CUSTOM_COLUMN_BOTTOM_RIGHT2, mColumnBottomRight2); } /** * To set a custom channel name view to instead of default widget. * * @param channelName custom TextView to show channel Name. */ public void setCustomChannelName(@NonNull TextView channelName) { mColumnChannelName.removeAllViews(); mColumnChannelName.setVisibility(VISIBLE); mColumnChannelName.addView(channelName); mChannelNameTextView = channelName; } /** * To set visibility of channel name TextView. * * @param visibility visibility for channel name. */ public void setChannelNameVisibility(int visibility) { mColumnChannelName.setVisibility(visibility); } /** * To set a custom error message view to instead of default widget. * * @param errorMessage custom TextView to show error message. */ public void setCustomErrorMessage(@NonNull TextView errorMessage) { mColumnErrorMessage.removeAllViews(); RelativeLayout errorBackground = (RelativeLayout) View.inflate(mThemeContext, R.layout.error_background, null); errorBackground.addView(errorMessage); mColumnErrorMessage.addView(errorBackground); mErrorMessageTextView = errorMessage; } /** * To set visibility of error message TextView. * * @param visibility visibility for error message. */ public void setErrorMessageVisibility(int visibility) { mColumnErrorMessage.setVisibility(visibility); } /** * To set a custom broadcast state message view to instead of default widget. * * @param message custom View to show broadcast state message. */ public void setCustomBroadcastState(@NonNull View message) { mColumnBroadcastState.removeAllViews(); mColumnBroadcastState.addView(message); mBroadcastStateView = message; } /** * To set visibility of broadcast state message TextView. * * @param visibility visibility for broadcast state message. */ public void setBroadcastStateVisibility(int visibility) { mColumnBroadcastState.setVisibility(visibility); } /** * To set a channel name TextView style via res id. * * @param resId a style res id which to style channel name TextView. */ public void setChannelNameAppearance(@StyleRes int resId) { if (mChannelNameTextView == null) { Log.e(TAG, "channel name text view is null."); return; } TextViewCompat.setTextAppearance(mChannelNameTextView, resId); } /** * To set a custom summary viewer view to instead of default widget. * * @param summaryViewer custom TextView to show summary viewer. */ public void setCustomSummaryViewerView(@NonNull TextView summaryViewer) { mColumnSummaryViewer.removeAllViews(); mColumnSummaryViewer.setVisibility(VISIBLE); mColumnSummaryViewer.addView(summaryViewer); mSummaryViewerTextView = summaryViewer; } /** * To set a summary viewer textview style via res id. * * @param resId a style res id which to style summary viewer TextView. */ public void setSummaryViewerAppearance(@StyleRes int resId) { if (mSummaryViewerTextView == null) { Log.e(TAG, "summary viewer text view is null."); return; } TextViewCompat.setTextAppearance(mSummaryViewerTextView, resId); } /** * To set visibility of summary viewer. * * @param visibility visibility for summary viewer. */ public void setSummaryViewerVisibility(int visibility) { mColumnSummaryViewer.setVisibility(visibility); } /** * To set visibility of content progress SeekBar. * * @param visibility visibility for content seek bar. */ public void setContentSeekBarVisibility(int visibility) { mColumnContentSeekBar.setVisibility(visibility); } /** * To set a custom contentSeekBar view to instead of default widget. * * @param contentSeekBar custom ContentSeekBar to show progress. */ public void setCustomContentSeekBar(@NonNull ContentSeekBar contentSeekBar) { mColumnContentSeekBar.removeAllViews(); mColumnContentSeekBar.setVisibility(VISIBLE); mColumnContentSeekBar.addView(contentSeekBar); mContentSeekBar = contentSeekBar; mContentSeekBar.setOnTrackingListener(mTrackingListener); mContentSeekBar.setLiveDvrPositionTimeStringListener(mLiveDvrPositionTimeStringListener); } /** * To set a custom text track view to instead of default widget. * * @param textTrackView custom TextView to show text track. */ public void setCustomTextTrack(@NonNull TextView textTrackView) { mTextTrack.removeAllViews(); mTextTrack.setVisibility(VISIBLE); mTextTrack.addView(textTrackView); mTextTrackView = textTrackView; } public void setTextTrackViewVisibility(int visibility) { visibility = isVideoHasTextTracks() ? visibility : GONE; if (mTextTrackView != null && mEnableDefaultTextTrack) { mTextTrackView.setVisibility(visibility); } } /** * To set a custom loadingProgressBar view to instead of default widget. * * @param progressBar custom ProgressBar to show loading while player is buffering. */ public void setCustomLoadingProgressBar(@NonNull ProgressBar progressBar) { mColumnLoadingBar.removeAllViews(); mColumnLoadingBar.addView(progressBar); } /** * To set visibility of loading ProgressBar. * * @param visible true for visible, false for gone. */ public void setLoadingProgressBarVisible(boolean visible) { mColumnLoadingBar.setVisibility(visible ? VISIBLE : GONE); } /** * To set switch speed position to other custom column. * * @param switchSpeedIcon the custom view to instead of default icon. * @param position this position which to set up icon. */ public void setSwitchSpeedViewPosition(@NonNull View switchSpeedIcon, @CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); ViewParent parent = null; if (mSwitchSpeedView != null) { parent = mSwitchSpeedView.getParent(); } if (parent != null && parent instanceof ViewGroup) { ((ViewGroup) (parent)).removeView(mSwitchSpeedView); ((ViewGroup) (parent)).setVisibility(GONE); } column.setVisibility(VISIBLE); column.removeAllViews(); column.addView(switchSpeedIcon); mSwitchSpeedView = switchSpeedIcon; mSwitchSpeedView.setBackgroundResource(mImageButtonBackground); mSwitchSpeedView.setOnClickListener(mSwitchSpeedClickListener); } /** * To set switch speed position to other custom column. * * @param position this position which to set up icon. */ public void setSwitchSpeedViewPosition(@CustomColumnPosition int position) { if (mSwitchSpeedView == null) { mSwitchSpeedView = View.inflate(mThemeContext, R.layout.switch_speed_layout, null); } setSwitchSpeedViewPosition(mSwitchSpeedView, position); } public void setSwitchSpeedViewVisibility(int viewVisibility) { if (mSwitchSpeedView != null && mEnableDefaultSwitchSpeedIcon) { mSwitchSpeedView.setVisibility(viewVisibility); } } /** * To set text track toggling to other custom column. * * @param textTrackToggle the custom view to instead of default toggle. * @param position this position which to set up icon. */ public void setTextTrackToggleViewPosition(@NonNull View textTrackToggle, @CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); ViewParent parent = null; if (mTextTrackToggle != null) { parent = mTextTrackToggle.getParent(); } if (parent != null && parent instanceof ViewGroup) { ((ViewGroup) (parent)).removeView(mTextTrackToggle); ((ViewGroup) (parent)).setVisibility(GONE); } column.setVisibility(VISIBLE); column.removeAllViews(); column.addView(textTrackToggle); mTextTrackToggle = textTrackToggle; mTextTrackToggle.setBackgroundResource(mImageButtonBackground); mTextTrackToggle.setOnClickListener(mTextTrackToggleClickListener); } /** * To set text track toggle position to other custom column. * * @param position this position which to set up icon. */ public void setTextTrackToggleViewPosition(@CustomColumnPosition int position) { if (mTextTrackToggle == null) { mTextTrackToggle = View.inflate(mThemeContext, R.layout.text_track_toggle, null); } setTextTrackToggleViewPosition(mTextTrackToggle, position); } public void setTextTrackToggleViewVisibility(int visibility) { visibility = isVideoHasTextTracks() ? visibility : GONE; if (mTextTrackToggle != null && mEnableDefaultTextTrackToggle) { mTextTrackToggle.setVisibility(visibility); } } private boolean isVideoHasTextTracks() { MediaMetadataCompat metadata = getMediaControllerCompat().getMetadata(); if (metadata.containsKey(VideoCustomMetadata.TEXT_TRACK_ID_ARRAY)) { String[] ids = metadata.getBundle().getStringArray(VideoCustomMetadata.TEXT_TRACK_ID_ARRAY); return ids != null && ids.length > 0; } else { return false; } } /** * To set switch quality position to other custom column. * * @param switchQuality the custom view to instead of default icon. * @param position this position which to set up icon. */ public void setSwitchQualityViewPosition(@NonNull View switchQuality, @CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); ViewParent parent = null; if (mSwitchQualityView != null) { parent = mSwitchQualityView.getParent(); } if (parent != null && parent instanceof ViewGroup) { ((ViewGroup) (parent)).removeView(mSwitchQualityView); ((ViewGroup) (parent)).setVisibility(GONE); } column.setVisibility(VISIBLE); column.removeAllViews(); column.addView(switchQuality); mSwitchQualityView = switchQuality; mSwitchQualityView.setBackgroundResource(mImageButtonBackground); mSwitchQualityView.setOnClickListener(mSwitchQualityClickListener); } /** * To set switch quality position to other custom column. * * @param position this position which to set up icon. */ public void setSwitchQualityViewPosition(@CustomColumnPosition int position) { if (mSwitchQualityView == null) { mSwitchQualityView = View.inflate(mThemeContext, R.layout.switch_quality_layout, null); } setSwitchQualityViewPosition(mSwitchQualityView, position); } /** * To enable default switch quality dialog to open when click switch quality icon view. * * @param enable true for enable, false for disable. */ public void setEnableDefaultSwitchDialog(boolean enable) { mEnableDefaultSwitchQualityDialog = enable; } /** * To set listener. If switch quality view is clicked, it will trigger listener. * * @param listener a listener to listen switch quality view click event. */ public void setOnClickSwitchQualityViewListener(SwitchQualityViewClickListener listener) { mSwitchQualityViewListener = listener; } /** * To set listener. If player throws error message, it will trigger this listener . * * @param listener a listener to listen error message. */ public void setOnErrorMessageThrowListener(ErrorMessageListener listener) { mErrorMessageListener = listener; } /** * To set custom view to specific custom column. * * @param customView this custom view. * @param position this position to set up custom view. */ public void setCustomViewToColumn(@NonNull View customView, @CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); column.setVisibility(VISIBLE); column.removeAllViews(); column.addView(customView); } /** * To remove view in specific column. * * @param position this position to remove view. */ public void removeViewFromCustomColumn(@CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); column.setVisibility(GONE); column.removeAllViews(); } /** * To remove views in all custom column. */ public void removeViewAllCustomColumn() { mColumnTopRight.removeAllViews(); mColumnTopRight.setVisibility(GONE); mColumnBottomLeft.removeAllViews(); mColumnBottomLeft.setVisibility(GONE); mColumnBottomRight1.removeAllViews(); mColumnBottomRight1.setVisibility(GONE); mColumnBottomRight2.removeAllViews(); mColumnBottomRight2.setVisibility(GONE); } /** * To set logo at specific position. * * @param resId the logo icon res id. * @param position this position to set up logo. */ public View setLogo(@DrawableRes int resId, @CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); ImageView imageView = null; if (mLogoView != null) { ViewParent parent = mLogoView.getParent(); if (parent != null && parent instanceof ViewGroup) { ((ViewGroup) (parent)).removeView(mLogoView); ((ViewGroup) (parent)).setVisibility(GONE); } } column.setVisibility(VISIBLE); column.removeAllViews(); imageView = new AppCompatImageView(mThemeContext); mLogoView = imageView; imageView.setImageResource(resId); column.addView(imageView); return imageView; } /** * To set custom play icon. * * @param resId the play icon res id. */ public void setCustomPlayIcon(@DrawableRes int resId) { ImageButton imageButton; mColumnPlay.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (!mIsBind && mStraasMediaCore != null) { mStraasMediaCore.setUiContainer(StraasPlayerView.this); } mCanToggleControllerUi = true; getMediaControllerCompat().getTransportControls().play(); resetPlayPauseUiWithControllerVisibility(); switchToPause(); Utils.toggleViewVisibilityWithAnimation(AUTO_HIDE_DELAY_MILLIS, mControllerContainer, mColumnPlayPause); } }); mColumnPlay.addView(imageButton); mColumnAdPlay.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mColumnAdPlay.setVisibility(GONE); getMediaControllerCompat().getTransportControls().play(); } }); mColumnAdPlay.addView(imageButton); } /** * To set custom pause icon. * * @param resId the pause icon res id. */ public void setCustomPauseIcon(@DrawableRes int resId) { ImageButton imageButton; mColumnPause.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mCanToggleControllerUi = false; getMediaControllerCompat().getTransportControls().pause(); showControllerUi(); showPlayUi(); } }); mColumnPause.addView(imageButton); } /** * To set custom replay icon. * * @param resId the replay icon res id. */ public void setCustomReplayIcon(@DrawableRes int resId) { ImageButton imageButton; mColumnReplay.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mCanToggleControllerUi = true; getMediaControllerCompat().getTransportControls().seekTo(0); switchToPause(); } }); mColumnReplay.addView(imageButton); } /** * To set custom skip-to-previous icon. * * @param resId the replay icon res id. */ public void setCustomSkipToPreviousIcon(@DrawableRes int resId) { ImageButton imageButton; mColumnPrevious.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { getMediaControllerCompat().getTransportControls().skipToPrevious(); } }); mColumnPrevious.addView(imageButton); } /** * To set custom skip-to-next icon. * * @param resId the replay icon res id. */ public void setCustomSkipToNextIcon(@DrawableRes int resId) { ImageButton imageButton; mColumnNext.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { getMediaControllerCompat().getTransportControls().skipToNext(); } }); mColumnNext.addView(imageButton); } public void setCustomDvrPlaybackAvailable(@NonNull View message) { mColumnDvrPlaybackAvailable.removeAllViews(); mColumnDvrPlaybackAvailable.addView(message); mDvrPlaybackAvailableView = message; } public void setDvrPlaybackAvailableVisibility(int visibility) { mColumnDvrPlaybackAvailable.setVisibility(visibility); } /** * To enable controller ui to show when touch screen. * * @param enable true for enable, false for disable. */ public void setAutoHideControllerUiWhenTouch(boolean enable) { if (enable) { mGestureDetector = mGestureTapDetector; } else { mGestureDetector = mGestureFakeDetector; } } /** * To add listener. If player is onConnected, it will trigger listeners. * * @param listener a listener to listen player onConnected event. */ public void addMediaConnectedListener(ConnectionCallback listener) { mMediaConnectedListenerList.add(listener); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { mGestureDetector.onTouchEvent(event); return super.onInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { mGestureDetector.onTouchEvent(event); return super.onTouchEvent(event); } else { return true; } } public void setTitle(CharSequence title) { if (mChannelNameTextView != null) { mChannelNameTextView.setText(title); } } private class ChannelNameMetadataListener { void onMetaChanged(TextView channelNameTextView, String channelName) { if (channelNameTextView != null && !TextUtils.isEmpty(channelName)) { channelNameTextView.setText(channelName); } } } private class SummaryViewerMetadataListener { void onMetaChanged(TextView summaryViewerTextView, long summaryViewer) { if (summaryViewerTextView != null) { summaryViewerTextView.setText(Utils.convertLong(summaryViewer)); } } } private class ErrorMessageListener { void onError(TextView errorMessageTextView, @ErrorReason.ErrorReasonType String errorType) { if (errorMessageTextView != null) { mColumnErrorMessage.setVisibility(VISIBLE); String message; switch (errorType) { case ErrorReason.NETWORK_ERROR: message = getContext().getString(R.string.network_no_connection); break; case ErrorReason.NOT_FOUND: message = getContext().getString(R.string.content_no_exist); break; case ErrorReason.NOT_PUBLIC: message = getContext().getString(R.string.content_no_public); break; case ErrorReason.MEDIA_PERMISSION_DENIAL: message = getContext().getString(R.string.access_permission_denial); break; case ErrorReason.TEMPORARILY_UNAVAILABLE: case ErrorReason.DATA_DESERIALIZE_ERROR: case ErrorReason.INTERNAL_ERROR: default: message = getContext().getString(R.string.common_error); break; } mErrorMessageTextView.setText(message); } } } private class LivePositionTimeListener { void onLivePositionTimeChanged(TextView livePositionTimeTextView, String timeString) { if (livePositionTimeTextView != null && !TextUtils.isEmpty(timeString)) { livePositionTimeTextView.setText(timeString); } } } private class BroadcastStateListener { void offline(View broadcastStateView) { if (broadcastStateView == null) { return; } TextView textView = broadcastStateView.findViewById(android.R.id.text1); if (textView == null) { return; } setErrorMessageVisibility(GONE); setBroadcastStateVisibility(VISIBLE); textView.setText(R.string.broadcast_state_offline); } void endEvent(View broadcastStateView) { if (broadcastStateView == null) { return; } TextView textView = broadcastStateView.findViewById(android.R.id.text1); if (textView == null) { return; } setErrorMessageVisibility(GONE); setBroadcastStateVisibility(VISIBLE); textView.setText(R.string.broadcast_state_ended); } void online() { setErrorMessageVisibility(GONE); setBroadcastStateVisibility(GONE); } void waitForStream(View broadcastStateView) { if (broadcastStateView == null) { return; } TextView textView = broadcastStateView.findViewById(android.R.id.text1); if (textView == null) { return; } setErrorMessageVisibility(GONE); setBroadcastStateVisibility(VISIBLE); textView.setText(R.string.broadcast_state_wait_for_stream); } void dvrPlaybackAvailable(View dvrPlaybackAvailableView) { if (dvrPlaybackAvailableView == null) { return; } TextView textView = dvrPlaybackAvailableView.findViewById(R.id.text_dvr_playback_end); if (textView == null) { return; } setErrorMessageVisibility(GONE); setBroadcastStateVisibility(GONE); setDvrPlaybackAvailableVisibility(VISIBLE); textView.setText(R.string.broadcast_state_offline); } } private MediaControllerCompat getMediaControllerCompat() { return MediaControllerCompat.getMediaController(mFragmentActivity); } private OnClickListener mSwitchQualityClickListener = new OnClickListener() { @Override public void onClick(final View view) { MediaControllerCompatHelper.getVideoQualityInfo(getMediaControllerCompat(), new VideoQualityInfoCallback() { @Override public void onGetVideoQualityInfo(VideoQualityInfo info) { if (mEnableDefaultSwitchQualityDialog) { SwitchQualityDialog dialog = SwitchQualityDialog.newInstance( info.mFormats, info.mCurrentSelectedIndex); dialog.show(mFragmentActivity.getSupportFragmentManager(), SwitchQualityDialog.class.getSimpleName()); } if (mSwitchQualityViewListener != null) { mSwitchQualityViewListener.onFormatCallback(info.mFormats, info.mCurrentSelectedIndex); } } }); } }; private OnClickListener mSwitchSpeedClickListener = new OnClickListener() { @Override public void onClick(final View view) { MediaControllerCompatHelper.getPlayerCurrentSpeed(getMediaControllerCompat(), new MediaControllerCompatHelper.PlayerSpeedCallback() { @Override public void onGetPlayerSpeed(float speed) { SwitchSpeedDialog dialog = new SwitchSpeedDialog() .setCurrentSpeed(speed) .setSpeedOption(new ArrayList<>(Arrays.asList(PLAYBACK_SPEED_OPTIONS))); dialog.show(mFragmentActivity.getSupportFragmentManager(), SwitchSpeedDialog.class.getSimpleName()); } }); } }; private OnClickListener mTextTrackToggleClickListener = new OnClickListener() { @Override public void onClick(final View view) { boolean enableTextTrack = !mTextTrackToggle.isActivated(); MediaControllerCompatHelper.setCaptionEnable(getMediaControllerCompat(), enableTextTrack); if (!enableTextTrack) { mTextTrackView.setVisibility(GONE); } } }; private ContentSeekBar.TrackingListener mTrackingListener = new ContentSeekBar.TrackingListener() { @Override public void onTrackingTouch(boolean isTracking) { if (isTracking) { Utils.stopAnimation(mControllerContainer, mColumnPlayPause); if (mIsLiveSeekable) { setBottomLeftColumnToLivePositionTime(); } } else { Utils.toggleViewVisibilityWithAnimation(AUTO_HIDE_DELAY_MILLIS, mControllerContainer, mColumnPlayPause); refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_DVR); } } }; private ContentSeekBar.LiveDvrPositionTimeStringListener mLiveDvrPositionTimeStringListener = new ContentSeekBar.LiveDvrPositionTimeStringListener() { @Override public void onLiveDvrPositionTimeStringChanged(String timeString) { mLivePositionTimeListener.onLivePositionTimeChanged(mLivePositionTimeTextView, timeString); } }; private OnClickListener mGrayLiveIconOnClickListener = new OnClickListener() { @Override public void onClick(View v) { if (!mIsBind && mStraasMediaCore != null) { mStraasMediaCore.setUiContainer(StraasPlayerView.this); } mCanToggleControllerUi = true; MediaControllerCompatHelper.playAtLiveEdge(getMediaControllerCompat()); resetPlayPauseUiWithControllerVisibility(); switchToPause(); Utils.toggleViewVisibilityWithAnimation(AUTO_HIDE_DELAY_MILLIS, mControllerContainer, mColumnPlayPause); refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_EDGE); } }; @Override protected void onDetachedFromWindow() { mMediaConnectedListenerList.clear(); if (mContentSeekBar != null) { mContentSeekBar.destroy(); } super.onDetachedFromWindow(); } @NonNull @Override public ViewGroup getVideoContainer() { return mVideoView; } @Nullable @Override public ViewGroup getAdContainer() { return mAdView; } @Override public void onUnbind(StraasMediaCore client) { mIsBind = false; mStraasMediaCore = client; MediaControllerCompat mediaControllerCompat = getMediaControllerCompat(); if (mediaControllerCompat != null) { mediaControllerCompat.unregisterCallback(mMediaControllerCallback); } if (mContentSeekBar != null) { mContentSeekBar.destroy(); } mCanToggleControllerUi = false; showControllerUi(); showPlayUi(); } @Override public void onMediaBrowserConnected(StraasMediaCore client) { mIsBind = true; if (mFragmentActivity == null) { Log.e(TAG, "It's not FragmentActivity."); return; } MediaControllerCompat.setMediaController(mFragmentActivity, client.getMediaController()); for (ConnectionCallback connectionCallback : mMediaConnectedListenerList) { connectionCallback.onConnected(); } mMediaControllerCallback.onExtrasChanged(getMediaControllerCompat().getExtras()); mMediaControllerCallback.onMetadataChanged(getMediaControllerCompat().getMetadata()); mMediaControllerCallback.onPlaybackStateChanged(getMediaControllerCompat().getPlaybackState()); mMediaControllerCallback.onQueueChanged(getMediaControllerCompat().getQueue()); mMediaControllerCallback.onQueueTitleChanged(getMediaControllerCompat().getQueueTitle()); getMediaControllerCompat().registerCallback(mMediaControllerCallback); if (mContentSeekBar != null) { mContentSeekBar.setMediaPlayer(new PlayerControl(mFragmentActivity, null)); } } @Override public void onMediaBrowserConnectionSuspended() { mIsBind = false; } @Override public void onMediaBrowserConnectionFailed() { mIsBind = false; } private void showControllerUi() { Utils.stopAnimation(mControllerContainer); Utils.resetAlpha(mControllerContainer); mControllerContainer.setVisibility(VISIBLE); } private void showPlayUi() { Utils.stopAnimation(mColumnPlayPause); Utils.resetAlpha(mColumnPlayPause); mColumnPlayPause.setVisibility(VISIBLE); switchToPlay(); } private void resetPlayPauseUiWithControllerVisibility() { if (mColumnPlayPause.getVisibility() != mControllerContainer.getVisibility()) { mColumnPlayPause.setVisibility(mControllerContainer.getVisibility()); } } private void switchToPlay() { mColumnPlay.setVisibility(VISIBLE); mColumnReplay.setVisibility(INVISIBLE); mColumnPause.setVisibility(INVISIBLE); } private void switchToPause() { mColumnPlay.setVisibility(INVISIBLE); mColumnReplay.setVisibility(INVISIBLE); mColumnPause.setVisibility(VISIBLE); setDvrPlaybackAvailableVisibility(INVISIBLE); } private void switchToReplay() { Bundle liveBundle = (mLiveBundle != null) ? mLiveBundle : getMediaControllerCompat().getExtras(); int broadcastStateV2 = liveBundle.getInt(LIVE_EXTRA_BROADCAST_STATE_V2, BROADCAST_STATE_UNKNOWN); if (broadcastStateV2 == BROADCAST_STATE_DVR_PLAYBACK_AVAILABLE && mIsLiveSeekable) { setDvrPlaybackAvailableVisibility(VISIBLE); refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_DVR); } else { mColumnReplay.setVisibility(VISIBLE); } mColumnPlay.setVisibility(INVISIBLE); mColumnPause.setVisibility(INVISIBLE); } private void switchMode(boolean isLive, boolean isLiveSeekable) { mIsLive = isLive; mIsLiveSeekable = isLiveSeekable; setPlaybackMode(isLive ? PLAYBACK_MODE_LIVE_EDGE : PLAYBACK_MODE_VOD); setColumnContentSeekBarMargin(); if (isLive) { setContentSeekBarVisibility(mIsLiveSeekable ? VISIBLE : GONE); setSummaryViewerVisibility(INVISIBLE); setSwitchSpeedViewVisibility(GONE); setTextTrackToggleViewVisibility(GONE); setTextTrackViewVisibility(GONE); setBottomLeftColumnToLiveIcon(true); } else { setContentSeekBarVisibility(VISIBLE); setSummaryViewerVisibility(VISIBLE); setSwitchSpeedViewVisibility(VISIBLE); setTextTrackToggleViewVisibility(VISIBLE); setTextTrackViewVisibility(VISIBLE); removeViewFromCustomColumn(CUSTOM_COLUMN_BOTTOM_LEFT); } } private void refreshLiveDvrUiStatus(@PlaybackMode int playbackMode) { if (!mIsLiveSeekable) { return; } switch(playbackMode) { case PLAYBACK_MODE_LIVE_EDGE: case PLAYBACK_MODE_LIVE_DVR: setPlaybackMode(playbackMode); setBottomLeftColumnToLiveIcon(playbackMode == PLAYBACK_MODE_LIVE_EDGE); break; case PLAYBACK_MODE_VOD: default: break; } } private void setPlaybackMode(@PlaybackMode int playbackMode) { mPlaybackMode = playbackMode; if (mContentSeekBar != null) { mContentSeekBar.setPlaybackMode(mPlaybackMode); } } private void setColumnContentSeekBarMargin() { // workaround to place different margins for vod & live-dvr respectively int leftMargin = getResources().getDimensionPixelSize(R.dimen.progress_bar_column_left_margin); int rightMargin = getResources().getDimensionPixelSize(R.dimen.progress_bar_column_left_margin); if (mIsLiveSeekable) { leftMargin = getResources().getDimensionPixelSize(R.dimen.progress_bar_column_live_dvr_left_margin); rightMargin = getResources().getDimensionPixelSize(R.dimen.progress_bar_column_live_dvr_right_margin); } if (mColumnContentSeekBar.getLayoutParams() instanceof MarginLayoutParams) { MarginLayoutParams params = (MarginLayoutParams) mColumnContentSeekBar.getLayoutParams(); params.setMargins(leftMargin, 0, rightMargin, 0); mColumnContentSeekBar.setLayoutParams(params); } } private void setBottomLeftColumnToLiveIcon(boolean isLiveEdge) { TextView live = (TextView) View.inflate(mThemeContext, R.layout.live_view, null); Drawable drawable = VectorDrawableCompat.create(getResources(), isLiveEdge ? R.drawable.ic_live_player : R.drawable.ic_live_dvr_player, null); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(live, drawable, null, null, null); live.setTextColor(getResources().getColor(isLiveEdge ? R.color.color_live : R.color.color_live_dvr)); live.setOnClickListener(isLiveEdge ? null : mGrayLiveIconOnClickListener); setCustomViewToColumn(live, CUSTOM_COLUMN_BOTTOM_LEFT); mLivePositionTimeTextView = null; } private void setBottomLeftColumnToLivePositionTime() { mLivePositionTimeTextView = (TextView) View.inflate(mThemeContext, R.layout.live_view, null); setCustomViewToColumn(mLivePositionTimeTextView, CUSTOM_COLUMN_BOTTOM_LEFT); } }
MediaCore/src/main/java/io/straas/android/media/demo/widget/StraasPlayerView.java
package io.straas.android.media.demo.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.os.Bundle; import android.support.annotation.DrawableRes; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StyleRes; import android.support.graphics.drawable.VectorDrawableCompat; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.support.v4.media.MediaBrowserCompat.ConnectionCallback; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaControllerCompat; import android.support.v4.media.session.MediaSessionCompat.QueueItem; import android.support.v4.media.session.PlaybackStateCompat; import android.support.v4.util.SparseArrayCompat; import android.support.v4.view.GestureDetectorCompat; import android.support.v4.widget.TextViewCompat; import android.support.v7.widget.AppCompatImageButton; import android.support.v7.widget.AppCompatImageView; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.android.exoplayer2.Format; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import io.straas.android.media.demo.MediaControllerCompatHelper; import io.straas.android.media.demo.MediaControllerCompatHelper.VideoQualityInfo; import io.straas.android.media.demo.MediaControllerCompatHelper.VideoQualityInfoCallback; import io.straas.android.media.demo.Utils; import io.straas.android.media.demo.widget.ui.ContentSeekBar; import io.straas.android.media.demo.widget.ui.SwitchQualityDialog; import io.straas.android.media.demo.widget.ui.SwitchSpeedDialog; import io.straas.android.sdk.demo.R; import io.straas.android.sdk.media.StraasMediaCore; import io.straas.android.sdk.media.StraasMediaCore.ErrorReason; import io.straas.android.sdk.media.VideoCustomMetadata; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_DVR_PLAYBACK_AVAILABLE; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_ENDED; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_STARTED; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_STOPPED; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_UNKNOWN; import static io.straas.android.sdk.media.LiveEventListener.BROADCAST_STATE_WAITING_FOR_STREAM; import static io.straas.android.sdk.media.StraasMediaCore.KEY_EXTRA_TEXT_TRACKS; import static io.straas.android.sdk.media.StraasMediaCore.LIVE_EXTRA_BROADCAST_STATE_V2; public final class StraasPlayerView extends FrameLayout implements StraasMediaCore.UiContainer { private static final String TAG = StraasPlayerView.class.getSimpleName(); public static final int PLAYBACK_MODE_VOD = 0; public static final int PLAYBACK_MODE_LIVE_EDGE = 1; public static final int PLAYBACK_MODE_LIVE_DVR = 2; @IntDef({PLAYBACK_MODE_VOD, PLAYBACK_MODE_LIVE_EDGE, PLAYBACK_MODE_LIVE_DVR}) @Retention(RetentionPolicy.CLASS) public @interface PlaybackMode {} private static final int AUTO_HIDE_DELAY_MILLIS = 3000; private final Float[] PLAYBACK_SPEED_OPTIONS = {0.5f, 1.0f, 1.5f, 2.0f}; private boolean mEnableDefaultWidget; private boolean mEnableDefaultSwitchQualityIcon; private boolean mEnableDefaultSwitchQualityDialog; private boolean mEnableDefaultSwitchSpeedIcon; private boolean mEnableDefaultTextTrackToggle; private boolean mEnableDefaultChannelName; private boolean mEnableDefaultSummaryViewer; private boolean mEnableDefaultLoadingProgressBar; private boolean mEnableDefaultContentSeekBar; private boolean mEnableDefaultTextTrack; private boolean mEnableDefaultPlay; private boolean mEnableDefaultPause; private boolean mEnableDefaultReplay; private boolean mEnableDefaultPrevious; private boolean mEnableDefaultNext; private boolean mEnableDefaultErrorMessage; private boolean mEnableDefaultBroadcastStateMessage; private boolean mIsBind; private boolean mIsLive = false; private boolean mIsLiveSeekable; @PlaybackMode private int mPlaybackMode = PLAYBACK_MODE_VOD; private boolean mCanToggleControllerUi = false; private View mControllerContainer; private View mColumnPlayPause; private ViewGroup mColumnSummaryViewer; private ViewGroup mColumnChannelName; private ViewGroup mColumnContentSeekBar; private ViewGroup mColumnLoadingBar; private ViewGroup mColumnPlay; private ViewGroup mColumnPause; private ViewGroup mColumnReplay; private ViewGroup mColumnPrevious; private ViewGroup mColumnNext; private ViewGroup mColumnDvrPlaybackAvailable; private ViewGroup mColumnAdPlay; private ViewGroup mColumnErrorMessage; private ViewGroup mColumnBroadcastState; private ViewGroup mColumnTopRight; private ViewGroup mColumnTopRight2; private ViewGroup mColumnBottomLeft; private ViewGroup mColumnBottomRight1; private ViewGroup mColumnBottomRight2; private TextView mChannelNameTextView; private TextView mSummaryViewerTextView; private TextView mErrorMessageTextView; private TextView mLivePositionTimeTextView; private View mBroadcastStateView; private View mSwitchQualityView; private View mSwitchSpeedView; private View mTextTrackToggle; private View mLogoView; private ContentSeekBar mContentSeekBar; private TextView mTextTrackView; private View mDvrPlaybackAvailableView; private FrameLayout mVideoView; private FrameLayout mAdView; private ViewGroup mTextTrack; private FragmentActivity mFragmentActivity; private Bundle mLiveBundle; private MediaMetadataCompat mLastMediaMetadata; private PlaybackStateCompat mLastPlaybackStateCompat; private StraasMediaCore mStraasMediaCore; private int mImageButtonBackground; private Context mThemeContext; private GestureDetectorCompat mGestureDetector, mGestureTapDetector, mGestureFakeDetector; private SwitchQualityViewClickListener mSwitchQualityViewListener; private ChannelNameMetadataListener mChannelNameMetadataListener = new ChannelNameMetadataListener(); private SummaryViewerMetadataListener mSummaryViewerMetadataListener = new SummaryViewerMetadataListener(); private ErrorMessageListener mErrorMessageListener = new ErrorMessageListener(); private LivePositionTimeListener mLivePositionTimeListener = new LivePositionTimeListener(); private BroadcastStateListener mBroadcastStateListener = new BroadcastStateListener(); private List<ConnectionCallback> mMediaConnectedListenerList = new ArrayList<>(); private SparseArrayCompat<ViewGroup> mCustomColumnList = new SparseArrayCompat<>(); private List<QueueItem> mLastQueueList; private int mUIBroadcastState = BROADCAST_STATE_UNKNOWN; public interface SwitchQualityViewClickListener { void onFormatCallback(ArrayList<Format> formats, int currentIndex); } public static final int CUSTOM_COLUMN_TOP_RIGHT = 0; public static final int CUSTOM_COLUMN_BOTTOM_LEFT = 1; public static final int CUSTOM_COLUMN_BOTTOM_RIGHT1 = 2; public static final int CUSTOM_COLUMN_BOTTOM_RIGHT2 = 3; public static final int CUSTOM_COLUMN_TOP_RIGHT2 = 4; @IntDef({CUSTOM_COLUMN_TOP_RIGHT, CUSTOM_COLUMN_BOTTOM_LEFT, CUSTOM_COLUMN_BOTTOM_RIGHT1, CUSTOM_COLUMN_BOTTOM_RIGHT2, CUSTOM_COLUMN_TOP_RIGHT2}) @Retention(RetentionPolicy.SOURCE) public @interface CustomColumnPosition { } public StraasPlayerView(Context context) { this(context, null); } public StraasPlayerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public StraasPlayerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StraasLayout, defStyleAttr, 0); getCustomizedAttr(typedArray); typedArray.recycle(); } /** * Initialize a StrassPlayerView, which can be used to generate layout and control UI. * * @param fragmentActivity A FragmentActivity which use StraasPlayerView. */ public void initialize(@NonNull FragmentActivity fragmentActivity) { initialize(fragmentActivity, null); } /** * Initialize a StrassPlayerView, which can be used to generate layout and control UI. * * @param fragmentActivity A FragmentActivity which use StraasPlayerView. * @param configuration A configuration for whether default widget to use or not. */ public void initialize(@NonNull FragmentActivity fragmentActivity, @Nullable StraasConfiguration configuration) { mFragmentActivity = fragmentActivity; if (configuration != null) { initConfiguration(configuration); } init(); } public Context getThemeContext() { return mThemeContext; } private void init() { ViewGroup straasMainContainer = (ViewGroup) LayoutInflater.from(getContext()) .inflate(R.layout.straas_main_container, this, false); mThemeContext = straasMainContainer.getContext(); int[] attr = new int[]{R.attr.selectableItemBackgroundBorderless}; TypedArray typedArray = mThemeContext.obtainStyledAttributes(attr); mImageButtonBackground = Build.VERSION.SDK_INT > 21 ? typedArray.getResourceId(0, 0) : 0; typedArray.recycle(); mControllerContainer = straasMainContainer.findViewById(R.id.controllerContainer); straasMainContainer.findViewById(R.id.upContainer).setBackground( new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[]{ContextCompat.getColor(mThemeContext, android.R.color.transparent), ContextCompat.getColor(mThemeContext, R.color.color_controller_background_dark)})); straasMainContainer.findViewById(R.id.bottomContainer).setBackground( new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{ContextCompat.getColor(mThemeContext, android.R.color.transparent), ContextCompat.getColor(mThemeContext, R.color.color_controller_background_dark)})); mVideoView = straasMainContainer.findViewById(R.id.videoSurfaceView); mTextTrack = straasMainContainer.findViewById(R.id.textTrack); initColumn(straasMainContainer); mGestureTapDetector = new GestureDetectorCompat(getContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent event) { if (!mCanToggleControllerUi) { return false; } Utils.toggleViewVisibilityWithAnimation(AUTO_HIDE_DELAY_MILLIS, mControllerContainer, mColumnPlayPause); return true; } @Override public boolean onDown(MotionEvent e) { return true; } }); mGestureFakeDetector = new GestureDetectorCompat(getContext(), new GestureDetector.SimpleOnGestureListener()); if (mEnableDefaultWidget) { if (mEnableDefaultSwitchQualityIcon) { View switchQualityView = View.inflate(mThemeContext, R.layout.switch_quality_layout, null); setSwitchQualityViewPosition(switchQualityView, CUSTOM_COLUMN_TOP_RIGHT); } if (mEnableDefaultSwitchSpeedIcon) { View switchQualityView = View.inflate(mThemeContext, R.layout.switch_speed_layout, null); setSwitchSpeedViewPosition(switchQualityView, CUSTOM_COLUMN_TOP_RIGHT2); } if (mEnableDefaultTextTrackToggle) { View textTrackToggleView = View.inflate(mThemeContext, R.layout.text_track_toggle, null); setTextTrackToggleViewPosition(textTrackToggleView, CUSTOM_COLUMN_BOTTOM_RIGHT2); } if (mEnableDefaultChannelName) { TextView channelNameTextView = (TextView) View.inflate(mThemeContext, R.layout.channel_name, null); setCustomChannelName(channelNameTextView); } if (mEnableDefaultSummaryViewer) { TextView summaryViewerTextView = (TextView) View.inflate(mThemeContext, R.layout.summary_viewer, null); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(summaryViewerTextView, VectorDrawableCompat.create(getResources(), R.drawable.ic_eye_24dp, null), null, null, null); setCustomSummaryViewerView(summaryViewerTextView); } if (mEnableDefaultLoadingProgressBar) { ProgressBar progressBar = (ProgressBar) View.inflate(mThemeContext, R.layout.loading_progress_bar, null); setCustomLoadingProgressBar(progressBar); } if (mEnableDefaultContentSeekBar) { ContentSeekBar contentSeekBar = new ContentSeekBar(mThemeContext); setCustomContentSeekBar(contentSeekBar); } if (mEnableDefaultTextTrack) { TextView textTrackView = (TextView) View.inflate(mThemeContext, R.layout.text_track, null); setCustomTextTrack(textTrackView); } if (mEnableDefaultPlay) { setCustomPlayIcon(R.drawable.ic_play_arrow_48dp); } if (mEnableDefaultPause) { setCustomPauseIcon(R.drawable.ic_pause_48dp); } if (mEnableDefaultReplay) { setCustomReplayIcon(R.drawable.ic_replay_48dp); } if (mEnableDefaultPrevious) { setCustomSkipToPreviousIcon(R.drawable.ic_skip_previous_48dp); } if (mEnableDefaultNext) { setCustomSkipToNextIcon(R.drawable.ic_skip_next_48px); } if (mEnableDefaultErrorMessage) { TextView errorMessageTextView = (TextView) View.inflate(mThemeContext, R.layout.error_message, null); Drawable drawable = VectorDrawableCompat.create(getResources(), R.drawable.ic_error_player, null); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(errorMessageTextView, drawable, null, null, null); setCustomErrorMessage(errorMessageTextView); } if (mEnableDefaultBroadcastStateMessage) { View broadcastStateOffline = View.inflate(mThemeContext, R.layout.broadcast_offline, null); setCustomBroadcastState(broadcastStateOffline); } } mAdView = straasMainContainer.findViewById(R.id.adSurfaceView); addView(straasMainContainer); setAutoHideControllerUiWhenTouch(true); } public void hideControllerViews() { mControllerContainer.setVisibility(GONE); mColumnPlayPause.setVisibility(GONE); mColumnAdPlay.setVisibility(GONE); mColumnLoadingBar.setVisibility(GONE); mColumnBroadcastState.setVisibility(GONE); mColumnErrorMessage.setVisibility(GONE); } private void initConfiguration(StraasConfiguration configuration) { mEnableDefaultWidget = configuration.isEnableDefaultWidget(); mEnableDefaultSwitchQualityIcon = configuration.isEnableDefaultSwitchQuality(); mEnableDefaultSwitchSpeedIcon = configuration.isEnableDefaultSwitchSpeed(); mEnableDefaultTextTrackToggle = configuration.isEnableDefaultTextTrackToggle(); mEnableDefaultChannelName = configuration.isEnableDefaultChannelName(); mEnableDefaultSummaryViewer = configuration.isEnableDefaultSummaryViewer(); mEnableDefaultLoadingProgressBar = configuration.isEnableDefaultLoadingProgressBar(); mEnableDefaultContentSeekBar = configuration.isEnableDefaultContentProgressBar(); mEnableDefaultTextTrack = configuration.isEnableDefaultTextTrack(); mEnableDefaultPlay = configuration.isEnableDefaultPlay(); mEnableDefaultPause = configuration.isEnableDefaultPause(); mEnableDefaultReplay = configuration.isEnableDefaultReplay(); mEnableDefaultPrevious = configuration.isEnableDefaultSkipToPrevious(); mEnableDefaultNext = configuration.isEnableDefaultSkipToNext(); mEnableDefaultErrorMessage = configuration.isEnableDefaultErrorMessage(); mEnableDefaultBroadcastStateMessage = configuration.isEnableDefaultBroadcastStateMessage(); } private final MediaControllerCompat.Callback mMediaControllerCallback = new MediaControllerCompat.Callback() { @Override public void onQueueChanged(List<QueueItem> queue) { mLastQueueList = queue; if (mLastQueueList == null) { mLastMediaMetadata = null; if (mColumnPrevious.getVisibility() != GONE) { mColumnPrevious.setVisibility(GONE); } if (mColumnNext.getVisibility() != GONE) { mColumnNext.setVisibility(GONE); } } } @Override public void onSessionDestroyed() { } @Override public void onMetadataChanged(MediaMetadataCompat metadata) { if (metadata == null || (mLastMediaMetadata != null && TextUtils.equals(metadata.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID), mLastMediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID)) && TextUtils.equals(metadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE), mLastMediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE)) && metadata.getBundle().getBoolean(VideoCustomMetadata.CUSTOM_METADATA_IS_LIVE_LOW_LATENCY_FIRST) == mLastMediaMetadata.getBundle().getBoolean(VideoCustomMetadata.CUSTOM_METADATA_IS_LIVE_LOW_LATENCY_FIRST))) { return; } mLastMediaMetadata = metadata; String mediaId = mLastMediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID); if (TextUtils.isEmpty(mediaId)) { return; } if (mediaId.startsWith(StraasMediaCore.LIVE_ID_PREFIX)) { boolean isLiveSeekable = metadata.getBundle().getBoolean(VideoCustomMetadata.LIVE_DVR_ENABLED) && !metadata.getBundle().getBoolean(VideoCustomMetadata.CUSTOM_METADATA_IS_LIVE_LOW_LATENCY_FIRST); switchMode(true, isLiveSeekable); Bundle liveBundle = (mLiveBundle != null) ? mLiveBundle : getMediaControllerCompat().getExtras(); if (isLiveSeekable) { setCustomDvrPlaybackAvailable(View.inflate(mThemeContext, R.layout.dvr_playback_available, null)); } handleMediaSessionExtra(liveBundle, true); } else { switchMode(false, false); } if (mLastQueueList != null) { if (mLastPlaybackStateCompat.getActiveQueueItemId() == 0) { if (mColumnPrevious.getVisibility() != GONE) { mColumnPrevious.setVisibility(GONE); } } else if (mColumnPrevious.getVisibility() != VISIBLE) { mColumnPrevious.setVisibility(VISIBLE); } if (mLastPlaybackStateCompat.getActiveQueueItemId() == mLastQueueList.size() - 1) { if (mColumnNext.getVisibility() != GONE) { mColumnNext.setVisibility(GONE); } } else if (mColumnNext.getVisibility() != VISIBLE) { mColumnNext.setVisibility(VISIBLE); } } String title = metadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE); long summaryViewer = metadata.getBundle().getLong(VideoCustomMetadata.PLAY_COUNT_SUM); mChannelNameMetadataListener.onMetaChanged(mChannelNameTextView, title); mSummaryViewerMetadataListener.onMetaChanged(mSummaryViewerTextView, summaryViewer); } @Override public void onCaptioningEnabledChanged(boolean enabled) { super.onCaptioningEnabledChanged(enabled); if (mTextTrackToggle != null) { mTextTrackToggle.setActivated(enabled); } } @Override public void onPlaybackStateChanged(PlaybackStateCompat state) { if (state == null || (mLastPlaybackStateCompat != null && mLastPlaybackStateCompat.getState() == state.getState() && mLastPlaybackStateCompat.getActiveQueueItemId() == state.getActiveQueueItemId())) { return; } if (mLastPlaybackStateCompat == null && mTextTrackView != null) { MediaControllerCompatHelper.setCaptionEnable(getMediaControllerCompat(), true); } mLastPlaybackStateCompat = state; if (!TextUtils.isEmpty(state.getErrorMessage())) { @ErrorReason.ErrorReasonType String errorType = state.getErrorMessage().toString(); mErrorMessageListener.onError(mErrorMessageTextView, errorType); if (mIsLive) { Bundle liveBundle = (mLiveBundle != null) ? mLiveBundle : getMediaControllerCompat().getExtras(); handleMediaSessionExtra(liveBundle, true); } if (getKeepScreenOn()) { setKeepScreenOn(false); } return; } if (mColumnErrorMessage.getVisibility() != GONE) { setErrorMessageVisibility(GONE); } if (state.getState() == PlaybackStateCompat.STATE_PLAYING) { setErrorMessageVisibility(GONE); setBroadcastStateVisibility(GONE); if (mControllerContainer.getVisibility() != GONE) { Utils.toggleViewVisibilityWithAnimation(AUTO_HIDE_DELAY_MILLIS, mControllerContainer, mColumnPlayPause); } } int loadingProgressBarVisibility = GONE; if (state.getActiveQueueItemId() == StraasMediaCore.AD_PLAYBACK_ID) { if (mControllerContainer.getVisibility() != GONE) { mControllerContainer.setVisibility(GONE); } if (mColumnPlayPause.getVisibility() != GONE) { mColumnPlayPause.setVisibility(GONE); } switch (state.getState()) { case PlaybackStateCompat.STATE_BUFFERING: loadingProgressBarVisibility = VISIBLE; break; case PlaybackStateCompat.STATE_PLAYING: mColumnAdPlay.setVisibility(GONE); mCanToggleControllerUi = false; break; case PlaybackStateCompat.STATE_PAUSED: mColumnAdPlay.setVisibility(VISIBLE); break; case PlaybackStateCompat.STATE_STOPPED: // After AD playing ends, SDK player will seek the live streaming to // the real-time coverage of live automatically for all kinds of live: // normal live, low latency, and live-dvr if (mIsLive) { refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_EDGE); } break; } } else { if (mColumnAdPlay.getVisibility() != GONE) { mColumnAdPlay.setVisibility(GONE); } switch (state.getState()) { case PlaybackStateCompat.STATE_BUFFERING: loadingProgressBarVisibility = VISIBLE; mColumnPlay.setVisibility(GONE); mColumnPause.setVisibility(GONE); break; case PlaybackStateCompat.STATE_PLAYING: mCanToggleControllerUi = true; switchToPause(); if (!getKeepScreenOn()) { setKeepScreenOn(true); } break; case PlaybackStateCompat.STATE_PAUSED: if (mPlaybackMode == PLAYBACK_MODE_LIVE_EDGE) { refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_DVR); } mCanToggleControllerUi = false; showControllerUi(); showPlayUi(); if (getKeepScreenOn()) { setKeepScreenOn(false); } break; case PlaybackStateCompat.STATE_NONE: mCanToggleControllerUi = false; hideControllerViews(); refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_EDGE); if (getKeepScreenOn()) { setKeepScreenOn(false); } case PlaybackStateCompat.STATE_STOPPED: mCanToggleControllerUi = true; if (mIsLive) { Bundle liveBundle = (mLiveBundle != null) ? mLiveBundle : getMediaControllerCompat().getExtras(); handleMediaSessionExtra(liveBundle, true); } switchToReplay(); if (getKeepScreenOn()) { setKeepScreenOn(false); } break; } } setLoadingProgressBarVisible(loadingProgressBarVisibility == VISIBLE); } @Override public void onSessionEvent(String event, Bundle extras) { switch (event) { case StraasMediaCore.EVENT_MEDIA_BROWSER_SERVICE_ERROR: mErrorMessageListener.onError(mErrorMessageTextView, extras.getString(StraasMediaCore.KEY_MEDIA_BROWSER_ERROR_REASON)); break; } } @Override public void onExtrasChanged(Bundle extras) { handleTextTrackExtra(extras); mLiveBundle = extras; if (!mIsLive) { return; } boolean isStopPlay = mLastPlaybackStateCompat != null && (mLastPlaybackStateCompat.getState() == PlaybackStateCompat.STATE_STOPPED || mLastPlaybackStateCompat.getState() == PlaybackStateCompat.STATE_NONE || mLastPlaybackStateCompat.getState() == PlaybackStateCompat.STATE_ERROR); handleMediaSessionExtra(extras, isStopPlay); } }; private void handleTextTrackExtra(Bundle extras) { if (mTextTrackView == null) { return; } if (extras.containsKey(KEY_EXTRA_TEXT_TRACKS) && getMediaControllerCompat().isCaptioningEnabled()) { ArrayList<CharSequence> texts = extras.getCharSequenceArrayList(KEY_EXTRA_TEXT_TRACKS); if (texts == null || texts.isEmpty()) { mTextTrackView.setVisibility(GONE); } else { SpannableStringBuilder builder = new SpannableStringBuilder(); for (CharSequence text : texts) { builder.append(text); if (texts.indexOf(text) != texts.size() - 1) { builder.append("\n"); } } mTextTrackView.setVisibility(VISIBLE); mTextTrackView.setText(builder.toString()); } } else { mTextTrackView.setVisibility(GONE); } } private void handleMediaSessionExtra(Bundle extras, boolean shouldShowStateUi) { int broadcastStateV2 = extras.getInt(LIVE_EXTRA_BROADCAST_STATE_V2, BROADCAST_STATE_UNKNOWN); if (broadcastStateV2 != BROADCAST_STATE_STARTED && !shouldShowStateUi) { return; } if (broadcastStateV2 == mUIBroadcastState) { return; } mUIBroadcastState = broadcastStateV2; switch (broadcastStateV2) { case BROADCAST_STATE_STARTED: mBroadcastStateListener.online(); break; case BROADCAST_STATE_WAITING_FOR_STREAM: mBroadcastStateListener.waitForStream(mBroadcastStateView); break; case BROADCAST_STATE_DVR_PLAYBACK_AVAILABLE: mBroadcastStateListener.dvrPlaybackAvailable(mDvrPlaybackAvailableView); break; case BROADCAST_STATE_STOPPED: mBroadcastStateListener.offline(mBroadcastStateView); break; case BROADCAST_STATE_ENDED: mBroadcastStateListener.endEvent(mBroadcastStateView); break; } } /** * To set a channel name metadata change event. If channel name metadata is changed, it will trigger this listener * * @param listener A listener to listen channel name metadata changed event. */ public void setChannelNameMetalistener(@NonNull ChannelNameMetadataListener listener) { mChannelNameMetadataListener = listener; } /** * To set a summary viewer metadata change event. If summary viewer metadata is changed, it will trigger this listener * * @param listener A listener to listen summary viewer metadata changed event. */ public void setSummaryViewerMetadataListener(@NonNull SummaryViewerMetadataListener listener) { mSummaryViewerMetadataListener = listener; } private void getCustomizedAttr(TypedArray typedArray) { mEnableDefaultWidget = typedArray.getBoolean(R.styleable.StraasLayout_defaultWidget, true); mEnableDefaultSwitchQualityIcon = typedArray.getBoolean(R.styleable.StraasLayout_defaultSwitchQualityIcon, true); mEnableDefaultSwitchQualityDialog = typedArray.getBoolean(R.styleable.StraasLayout_defaultSwitchQualityDialog, true); mEnableDefaultSwitchSpeedIcon = typedArray.getBoolean(R.styleable.StraasLayout_defaultSwitchSpeedIcon, true); mEnableDefaultTextTrackToggle = typedArray.getBoolean(R.styleable.StraasLayout_defaultSwitchSpeedIcon, true); mEnableDefaultChannelName = typedArray.getBoolean(R.styleable.StraasLayout_defaultChannelName, true); mEnableDefaultSummaryViewer = typedArray.getBoolean(R.styleable.StraasLayout_defaultSummaryViewer, true); mEnableDefaultLoadingProgressBar = typedArray.getBoolean(R.styleable.StraasLayout_defaultLoadingProgressBar, true); mEnableDefaultContentSeekBar = typedArray.getBoolean(R.styleable.StraasLayout_defaultContentSeekbar, true); mEnableDefaultTextTrack = typedArray.getBoolean(R.styleable.StraasLayout_defaultTextTrack, true); mEnableDefaultPlay = typedArray.getBoolean(R.styleable.StraasLayout_defaultPlay, true); mEnableDefaultPause = typedArray.getBoolean(R.styleable.StraasLayout_defaultPause, true); mEnableDefaultReplay = typedArray.getBoolean(R.styleable.StraasLayout_defaultReplay, true); mEnableDefaultPrevious = typedArray.getBoolean(R.styleable.StraasLayout_defaultSkipToPrevious, true); mEnableDefaultNext = typedArray.getBoolean(R.styleable.StraasLayout_defaultSkipToNext, true); mEnableDefaultErrorMessage = typedArray.getBoolean(R.styleable.StraasLayout_defaultErrorMessage, true); mEnableDefaultBroadcastStateMessage = typedArray.getBoolean(R.styleable.StraasLayout_defaultBroadcastStateMessage, true); } private void initColumn(View root) { mColumnSummaryViewer = root.findViewById(R.id.summaryViewerColumn); mColumnChannelName = root.findViewById(R.id.channelNameColumn); mColumnLoadingBar = root.findViewById(R.id.loadingBarProgressColumn); mColumnContentSeekBar = root.findViewById(R.id.contentProgressBarColumn); mColumnPlay = root.findViewById(R.id.playColumn); mColumnPause = root.findViewById(R.id.pauseColumn); mColumnReplay = root.findViewById(R.id.replayColumn); mColumnPrevious = root.findViewById(R.id.previousColumn); mColumnNext = root.findViewById(R.id.nextColumn); mColumnPlayPause = root.findViewById(R.id.playPauseColumn); mColumnDvrPlaybackAvailable = root.findViewById(R.id.dvrPlaybackAvailableColumn); mColumnAdPlay = root.findViewById(R.id.adPlayColumn); mColumnErrorMessage = root.findViewById(R.id.errorMessageColumn); mColumnBroadcastState = root.findViewById(R.id.onLineOfflineColumn); mColumnTopRight = root.findViewById(R.id.customColumnTopRight); mColumnTopRight2 = root.findViewById(R.id.customColumnTopRight2); mColumnBottomLeft = root.findViewById(R.id.bottomLeftColumn); mColumnBottomRight1 = root.findViewById(R.id.bottomRightColumn1); mColumnBottomRight2 = root.findViewById(R.id.bottomRightColumn2); mCustomColumnList.put(CUSTOM_COLUMN_TOP_RIGHT, mColumnTopRight); mCustomColumnList.put(CUSTOM_COLUMN_TOP_RIGHT2, mColumnTopRight2); mCustomColumnList.put(CUSTOM_COLUMN_BOTTOM_LEFT, mColumnBottomLeft); mCustomColumnList.put(CUSTOM_COLUMN_BOTTOM_RIGHT1, mColumnBottomRight1); mCustomColumnList.put(CUSTOM_COLUMN_BOTTOM_RIGHT2, mColumnBottomRight2); } /** * To set a custom channel name view to instead of default widget. * * @param channelName custom TextView to show channel Name. */ public void setCustomChannelName(@NonNull TextView channelName) { mColumnChannelName.removeAllViews(); mColumnChannelName.setVisibility(VISIBLE); mColumnChannelName.addView(channelName); mChannelNameTextView = channelName; } /** * To set visibility of channel name TextView. * * @param visibility visibility for channel name. */ public void setChannelNameVisibility(int visibility) { mColumnChannelName.setVisibility(visibility); } /** * To set a custom error message view to instead of default widget. * * @param errorMessage custom TextView to show error message. */ public void setCustomErrorMessage(@NonNull TextView errorMessage) { mColumnErrorMessage.removeAllViews(); RelativeLayout errorBackground = (RelativeLayout) View.inflate(mThemeContext, R.layout.error_background, null); errorBackground.addView(errorMessage); mColumnErrorMessage.addView(errorBackground); mErrorMessageTextView = errorMessage; } /** * To set visibility of error message TextView. * * @param visibility visibility for error message. */ public void setErrorMessageVisibility(int visibility) { mColumnErrorMessage.setVisibility(visibility); } /** * To set a custom broadcast state message view to instead of default widget. * * @param message custom View to show broadcast state message. */ public void setCustomBroadcastState(@NonNull View message) { mColumnBroadcastState.removeAllViews(); mColumnBroadcastState.addView(message); mBroadcastStateView = message; } /** * To set visibility of broadcast state message TextView. * * @param visibility visibility for broadcast state message. */ public void setBroadcastStateVisibility(int visibility) { mColumnBroadcastState.setVisibility(visibility); } /** * To set a channel name TextView style via res id. * * @param resId a style res id which to style channel name TextView. */ public void setChannelNameAppearance(@StyleRes int resId) { if (mChannelNameTextView == null) { Log.e(TAG, "channel name text view is null."); return; } TextViewCompat.setTextAppearance(mChannelNameTextView, resId); } /** * To set a custom summary viewer view to instead of default widget. * * @param summaryViewer custom TextView to show summary viewer. */ public void setCustomSummaryViewerView(@NonNull TextView summaryViewer) { mColumnSummaryViewer.removeAllViews(); mColumnSummaryViewer.setVisibility(VISIBLE); mColumnSummaryViewer.addView(summaryViewer); mSummaryViewerTextView = summaryViewer; } /** * To set a summary viewer textview style via res id. * * @param resId a style res id which to style summary viewer TextView. */ public void setSummaryViewerAppearance(@StyleRes int resId) { if (mSummaryViewerTextView == null) { Log.e(TAG, "summary viewer text view is null."); return; } TextViewCompat.setTextAppearance(mSummaryViewerTextView, resId); } /** * To set visibility of summary viewer. * * @param visibility visibility for summary viewer. */ public void setSummaryViewerVisibility(int visibility) { mColumnSummaryViewer.setVisibility(visibility); } /** * To set visibility of content progress SeekBar. * * @param visibility visibility for content seek bar. */ public void setContentSeekBarVisibility(int visibility) { mColumnContentSeekBar.setVisibility(visibility); } /** * To set a custom contentSeekBar view to instead of default widget. * * @param contentSeekBar custom ContentSeekBar to show progress. */ public void setCustomContentSeekBar(@NonNull ContentSeekBar contentSeekBar) { mColumnContentSeekBar.removeAllViews(); mColumnContentSeekBar.setVisibility(VISIBLE); mColumnContentSeekBar.addView(contentSeekBar); mContentSeekBar = contentSeekBar; mContentSeekBar.setOnTrackingListener(mTrackingListener); mContentSeekBar.setLiveDvrPositionTimeStringListener(mLiveDvrPositionTimeStringListener); } /** * To set a custom text track view to instead of default widget. * * @param textTrackView custom TextView to show text track. */ public void setCustomTextTrack(@NonNull TextView textTrackView) { mTextTrack.removeAllViews(); mTextTrack.setVisibility(VISIBLE); mTextTrack.addView(textTrackView); mTextTrackView = textTrackView; } public void setTextTrackViewVisibility(int visibility) { visibility = isVideoHasTextTracks() ? visibility : GONE; if (mTextTrackView != null && mEnableDefaultTextTrack) { mTextTrackView.setVisibility(visibility); } } /** * To set a custom loadingProgressBar view to instead of default widget. * * @param progressBar custom ProgressBar to show loading while player is buffering. */ public void setCustomLoadingProgressBar(@NonNull ProgressBar progressBar) { mColumnLoadingBar.removeAllViews(); mColumnLoadingBar.addView(progressBar); } /** * To set visibility of loading ProgressBar. * * @param visible true for visible, false for gone. */ public void setLoadingProgressBarVisible(boolean visible) { mColumnLoadingBar.setVisibility(visible ? VISIBLE : GONE); } /** * To set switch speed position to other custom column. * * @param switchSpeedIcon the custom view to instead of default icon. * @param position this position which to set up icon. */ public void setSwitchSpeedViewPosition(@NonNull View switchSpeedIcon, @CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); ViewParent parent = null; if (mSwitchSpeedView != null) { parent = mSwitchSpeedView.getParent(); } if (parent != null && parent instanceof ViewGroup) { ((ViewGroup) (parent)).removeView(mSwitchSpeedView); ((ViewGroup) (parent)).setVisibility(GONE); } column.setVisibility(VISIBLE); column.removeAllViews(); column.addView(switchSpeedIcon); mSwitchSpeedView = switchSpeedIcon; mSwitchSpeedView.setBackgroundResource(mImageButtonBackground); mSwitchSpeedView.setOnClickListener(mSwitchSpeedClickListener); } /** * To set switch speed position to other custom column. * * @param position this position which to set up icon. */ public void setSwitchSpeedViewPosition(@CustomColumnPosition int position) { if (mSwitchSpeedView == null) { mSwitchSpeedView = View.inflate(mThemeContext, R.layout.switch_speed_layout, null); } setSwitchSpeedViewPosition(mSwitchSpeedView, position); } public void setSwitchSpeedViewVisibility(int viewVisibility) { if (mSwitchSpeedView != null && mEnableDefaultSwitchSpeedIcon) { mSwitchSpeedView.setVisibility(viewVisibility); } } /** * To set text track toggling to other custom column. * * @param textTrackToggle the custom view to instead of default toggle. * @param position this position which to set up icon. */ public void setTextTrackToggleViewPosition(@NonNull View textTrackToggle, @CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); ViewParent parent = null; if (mTextTrackToggle != null) { parent = mTextTrackToggle.getParent(); } if (parent != null && parent instanceof ViewGroup) { ((ViewGroup) (parent)).removeView(mTextTrackToggle); ((ViewGroup) (parent)).setVisibility(GONE); } column.setVisibility(VISIBLE); column.removeAllViews(); column.addView(textTrackToggle); mTextTrackToggle = textTrackToggle; mTextTrackToggle.setBackgroundResource(mImageButtonBackground); mTextTrackToggle.setOnClickListener(mTextTrackToggleClickListener); } /** * To set text track toggle position to other custom column. * * @param position this position which to set up icon. */ public void setTextTrackToggleViewPosition(@CustomColumnPosition int position) { if (mTextTrackToggle == null) { mTextTrackToggle = View.inflate(mThemeContext, R.layout.text_track_toggle, null); } setTextTrackToggleViewPosition(mTextTrackToggle, position); } public void setTextTrackToggleViewVisibility(int visibility) { visibility = isVideoHasTextTracks() ? visibility : GONE; if (mTextTrackToggle != null && mEnableDefaultTextTrackToggle) { mTextTrackToggle.setVisibility(visibility); } } private boolean isVideoHasTextTracks() { MediaMetadataCompat metadata = getMediaControllerCompat().getMetadata(); if (metadata.containsKey(VideoCustomMetadata.TEXT_TRACK_ID_ARRAY)) { String[] ids = metadata.getBundle().getStringArray(VideoCustomMetadata.TEXT_TRACK_ID_ARRAY); return ids != null && ids.length > 0; } else { return false; } } /** * To set switch quality position to other custom column. * * @param switchQuality the custom view to instead of default icon. * @param position this position which to set up icon. */ public void setSwitchQualityViewPosition(@NonNull View switchQuality, @CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); ViewParent parent = null; if (mSwitchQualityView != null) { parent = mSwitchQualityView.getParent(); } if (parent != null && parent instanceof ViewGroup) { ((ViewGroup) (parent)).removeView(mSwitchQualityView); ((ViewGroup) (parent)).setVisibility(GONE); } column.setVisibility(VISIBLE); column.removeAllViews(); column.addView(switchQuality); mSwitchQualityView = switchQuality; mSwitchQualityView.setBackgroundResource(mImageButtonBackground); mSwitchQualityView.setOnClickListener(mSwitchQualityClickListener); } /** * To set switch quality position to other custom column. * * @param position this position which to set up icon. */ public void setSwitchQualityViewPosition(@CustomColumnPosition int position) { if (mSwitchQualityView == null) { mSwitchQualityView = View.inflate(mThemeContext, R.layout.switch_quality_layout, null); } setSwitchQualityViewPosition(mSwitchQualityView, position); } /** * To enable default switch quality dialog to open when click switch quality icon view. * * @param enable true for enable, false for disable. */ public void setEnableDefaultSwitchDialog(boolean enable) { mEnableDefaultSwitchQualityDialog = enable; } /** * To set listener. If switch quality view is clicked, it will trigger listener. * * @param listener a listener to listen switch quality view click event. */ public void setOnClickSwitchQualityViewListener(SwitchQualityViewClickListener listener) { mSwitchQualityViewListener = listener; } /** * To set listener. If player throws error message, it will trigger this listener . * * @param listener a listener to listen error message. */ public void setOnErrorMessageThrowListener(ErrorMessageListener listener) { mErrorMessageListener = listener; } /** * To set custom view to specific custom column. * * @param customView this custom view. * @param position this position to set up custom view. */ public void setCustomViewToColumn(@NonNull View customView, @CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); column.setVisibility(VISIBLE); column.removeAllViews(); column.addView(customView); } /** * To remove view in specific column. * * @param position this position to remove view. */ public void removeViewFromCustomColumn(@CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); column.setVisibility(GONE); column.removeAllViews(); } /** * To remove views in all custom column. */ public void removeViewAllCustomColumn() { mColumnTopRight.removeAllViews(); mColumnTopRight.setVisibility(GONE); mColumnBottomLeft.removeAllViews(); mColumnBottomLeft.setVisibility(GONE); mColumnBottomRight1.removeAllViews(); mColumnBottomRight1.setVisibility(GONE); mColumnBottomRight2.removeAllViews(); mColumnBottomRight2.setVisibility(GONE); } /** * To set logo at specific position. * * @param resId the logo icon res id. * @param position this position to set up logo. */ public View setLogo(@DrawableRes int resId, @CustomColumnPosition int position) { ViewGroup column = mCustomColumnList.get(position); ImageView imageView = null; if (mLogoView != null) { ViewParent parent = mLogoView.getParent(); if (parent != null && parent instanceof ViewGroup) { ((ViewGroup) (parent)).removeView(mLogoView); ((ViewGroup) (parent)).setVisibility(GONE); } } column.setVisibility(VISIBLE); column.removeAllViews(); imageView = new AppCompatImageView(mThemeContext); mLogoView = imageView; imageView.setImageResource(resId); column.addView(imageView); return imageView; } /** * To set custom play icon. * * @param resId the play icon res id. */ public void setCustomPlayIcon(@DrawableRes int resId) { ImageButton imageButton; mColumnPlay.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (!mIsBind && mStraasMediaCore != null) { mStraasMediaCore.setUiContainer(StraasPlayerView.this); } mCanToggleControllerUi = true; getMediaControllerCompat().getTransportControls().play(); resetPlayPauseUiWithControllerVisibility(); switchToPause(); Utils.toggleViewVisibilityWithAnimation(AUTO_HIDE_DELAY_MILLIS, mControllerContainer, mColumnPlayPause); } }); mColumnPlay.addView(imageButton); mColumnAdPlay.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mColumnAdPlay.setVisibility(GONE); getMediaControllerCompat().getTransportControls().play(); } }); mColumnAdPlay.addView(imageButton); } /** * To set custom pause icon. * * @param resId the pause icon res id. */ public void setCustomPauseIcon(@DrawableRes int resId) { ImageButton imageButton; mColumnPause.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mCanToggleControllerUi = false; getMediaControllerCompat().getTransportControls().pause(); showControllerUi(); showPlayUi(); } }); mColumnPause.addView(imageButton); } /** * To set custom replay icon. * * @param resId the replay icon res id. */ public void setCustomReplayIcon(@DrawableRes int resId) { ImageButton imageButton; mColumnReplay.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mCanToggleControllerUi = true; getMediaControllerCompat().getTransportControls().seekTo(0); switchToPause(); } }); mColumnReplay.addView(imageButton); } /** * To set custom skip-to-previous icon. * * @param resId the replay icon res id. */ public void setCustomSkipToPreviousIcon(@DrawableRes int resId) { ImageButton imageButton; mColumnPrevious.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { getMediaControllerCompat().getTransportControls().skipToPrevious(); } }); mColumnPrevious.addView(imageButton); } /** * To set custom skip-to-next icon. * * @param resId the replay icon res id. */ public void setCustomSkipToNextIcon(@DrawableRes int resId) { ImageButton imageButton; mColumnNext.removeAllViews(); imageButton = new AppCompatImageButton(mThemeContext); imageButton.setImageResource(resId); imageButton.setBackgroundResource(mImageButtonBackground); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { getMediaControllerCompat().getTransportControls().skipToNext(); } }); mColumnNext.addView(imageButton); } public void setCustomDvrPlaybackAvailable(@NonNull View message) { mColumnDvrPlaybackAvailable.removeAllViews(); mColumnDvrPlaybackAvailable.addView(message); mDvrPlaybackAvailableView = message; } public void setDvrPlaybackAvailableVisibility(int visibility) { mColumnDvrPlaybackAvailable.setVisibility(visibility); } /** * To enable controller ui to show when touch screen. * * @param enable true for enable, false for disable. */ public void setAutoHideControllerUiWhenTouch(boolean enable) { if (enable) { mGestureDetector = mGestureTapDetector; } else { mGestureDetector = mGestureFakeDetector; } } /** * To add listener. If player is onConnected, it will trigger listeners. * * @param listener a listener to listen player onConnected event. */ public void addMediaConnectedListener(ConnectionCallback listener) { mMediaConnectedListenerList.add(listener); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { mGestureDetector.onTouchEvent(event); return super.onInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { mGestureDetector.onTouchEvent(event); return super.onTouchEvent(event); } else { return true; } } public void setTitle(CharSequence title) { if (mChannelNameTextView != null) { mChannelNameTextView.setText(title); } } private class ChannelNameMetadataListener { void onMetaChanged(TextView channelNameTextView, String channelName) { if (channelNameTextView != null && !TextUtils.isEmpty(channelName)) { channelNameTextView.setText(channelName); } } } private class SummaryViewerMetadataListener { void onMetaChanged(TextView summaryViewerTextView, long summaryViewer) { if (summaryViewerTextView != null) { summaryViewerTextView.setText(Utils.convertLong(summaryViewer)); } } } private class ErrorMessageListener { void onError(TextView errorMessageTextView, @ErrorReason.ErrorReasonType String errorType) { if (errorMessageTextView != null) { mColumnErrorMessage.setVisibility(VISIBLE); String message; switch (errorType) { case ErrorReason.NETWORK_ERROR: message = getContext().getString(R.string.network_no_connection); break; case ErrorReason.NOT_FOUND: message = getContext().getString(R.string.content_no_exist); break; case ErrorReason.NOT_PUBLIC: message = getContext().getString(R.string.content_no_public); break; case ErrorReason.MEDIA_PERMISSION_DENIAL: message = getContext().getString(R.string.access_permission_denial); break; case ErrorReason.TEMPORARILY_UNAVAILABLE: case ErrorReason.DATA_DESERIALIZE_ERROR: case ErrorReason.INTERNAL_ERROR: default: message = getContext().getString(R.string.common_error); break; } mErrorMessageTextView.setText(message); } } } private class LivePositionTimeListener { void onLivePositionTimeChanged(TextView livePositionTimeTextView, String timeString) { if (livePositionTimeTextView != null && !TextUtils.isEmpty(timeString)) { livePositionTimeTextView.setText(timeString); } } } private class BroadcastStateListener { void offline(View broadcastStateView) { if (broadcastStateView == null) { return; } TextView textView = broadcastStateView.findViewById(android.R.id.text1); if (textView == null) { return; } setErrorMessageVisibility(GONE); setBroadcastStateVisibility(VISIBLE); textView.setText(R.string.broadcast_state_offline); } void endEvent(View broadcastStateView) { if (broadcastStateView == null) { return; } TextView textView = broadcastStateView.findViewById(android.R.id.text1); if (textView == null) { return; } setErrorMessageVisibility(GONE); setBroadcastStateVisibility(VISIBLE); textView.setText(R.string.broadcast_state_ended); } void online() { setErrorMessageVisibility(GONE); setBroadcastStateVisibility(GONE); } void waitForStream(View broadcastStateView) { if (broadcastStateView == null) { return; } TextView textView = broadcastStateView.findViewById(android.R.id.text1); if (textView == null) { return; } setErrorMessageVisibility(GONE); setBroadcastStateVisibility(VISIBLE); textView.setText(R.string.broadcast_state_wait_for_stream); } void dvrPlaybackAvailable(View dvrPlaybackAvailableView) { if (dvrPlaybackAvailableView == null) { return; } TextView textView = dvrPlaybackAvailableView.findViewById(R.id.text_dvr_playback_end); if (textView == null) { return; } setErrorMessageVisibility(GONE); setBroadcastStateVisibility(GONE); setDvrPlaybackAvailableVisibility(VISIBLE); textView.setText(R.string.broadcast_state_offline); } } private MediaControllerCompat getMediaControllerCompat() { return MediaControllerCompat.getMediaController(mFragmentActivity); } private OnClickListener mSwitchQualityClickListener = new OnClickListener() { @Override public void onClick(final View view) { MediaControllerCompatHelper.getVideoQualityInfo(getMediaControllerCompat(), new VideoQualityInfoCallback() { @Override public void onGetVideoQualityInfo(VideoQualityInfo info) { if (mEnableDefaultSwitchQualityDialog) { SwitchQualityDialog dialog = SwitchQualityDialog.newInstance( info.mFormats, info.mCurrentSelectedIndex); dialog.show(mFragmentActivity.getSupportFragmentManager(), SwitchQualityDialog.class.getSimpleName()); } if (mSwitchQualityViewListener != null) { mSwitchQualityViewListener.onFormatCallback(info.mFormats, info.mCurrentSelectedIndex); } } }); } }; private OnClickListener mSwitchSpeedClickListener = new OnClickListener() { @Override public void onClick(final View view) { MediaControllerCompatHelper.getPlayerCurrentSpeed(getMediaControllerCompat(), new MediaControllerCompatHelper.PlayerSpeedCallback() { @Override public void onGetPlayerSpeed(float speed) { SwitchSpeedDialog dialog = new SwitchSpeedDialog() .setCurrentSpeed(speed) .setSpeedOption(new ArrayList<>(Arrays.asList(PLAYBACK_SPEED_OPTIONS))); dialog.show(mFragmentActivity.getSupportFragmentManager(), SwitchSpeedDialog.class.getSimpleName()); } }); } }; private OnClickListener mTextTrackToggleClickListener = new OnClickListener() { @Override public void onClick(final View view) { boolean enableTextTrack = !mTextTrackToggle.isActivated(); MediaControllerCompatHelper.setCaptionEnable(getMediaControllerCompat(), enableTextTrack); if (!enableTextTrack) { mTextTrackView.setVisibility(GONE); } } }; private ContentSeekBar.TrackingListener mTrackingListener = new ContentSeekBar.TrackingListener() { @Override public void onTrackingTouch(boolean isTracking) { if (isTracking) { Utils.stopAnimation(mControllerContainer, mColumnPlayPause); if (mIsLiveSeekable) { setBottomLeftColumnToLivePositionTime(); } } else { Utils.toggleViewVisibilityWithAnimation(AUTO_HIDE_DELAY_MILLIS, mControllerContainer, mColumnPlayPause); refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_DVR); } } }; private ContentSeekBar.LiveDvrPositionTimeStringListener mLiveDvrPositionTimeStringListener = new ContentSeekBar.LiveDvrPositionTimeStringListener() { @Override public void onLiveDvrPositionTimeStringChanged(String timeString) { mLivePositionTimeListener.onLivePositionTimeChanged(mLivePositionTimeTextView, timeString); } }; private OnClickListener mGrayLiveIconOnClickListener = new OnClickListener() { @Override public void onClick(View v) { if (!mIsBind && mStraasMediaCore != null) { mStraasMediaCore.setUiContainer(StraasPlayerView.this); } mCanToggleControllerUi = true; MediaControllerCompatHelper.playAtLiveEdge(getMediaControllerCompat()); resetPlayPauseUiWithControllerVisibility(); switchToPause(); Utils.toggleViewVisibilityWithAnimation(AUTO_HIDE_DELAY_MILLIS, mControllerContainer, mColumnPlayPause); refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_EDGE); } }; @Override protected void onDetachedFromWindow() { mMediaConnectedListenerList.clear(); if (mContentSeekBar != null) { mContentSeekBar.destroy(); } super.onDetachedFromWindow(); } @NonNull @Override public ViewGroup getVideoContainer() { return mVideoView; } @Nullable @Override public ViewGroup getAdContainer() { return mAdView; } @Override public void onUnbind(StraasMediaCore client) { mIsBind = false; mStraasMediaCore = client; MediaControllerCompat mediaControllerCompat = getMediaControllerCompat(); if (mediaControllerCompat != null) { mediaControllerCompat.unregisterCallback(mMediaControllerCallback); } if (mContentSeekBar != null) { mContentSeekBar.destroy(); } mCanToggleControllerUi = false; showControllerUi(); showPlayUi(); } @Override public void onMediaBrowserConnected(StraasMediaCore client) { mIsBind = true; if (mFragmentActivity == null) { Log.e(TAG, "It's not FragmentActivity."); return; } MediaControllerCompat.setMediaController(mFragmentActivity, client.getMediaController()); for (ConnectionCallback connectionCallback : mMediaConnectedListenerList) { connectionCallback.onConnected(); } mMediaControllerCallback.onExtrasChanged(getMediaControllerCompat().getExtras()); mMediaControllerCallback.onMetadataChanged(getMediaControllerCompat().getMetadata()); mMediaControllerCallback.onPlaybackStateChanged(getMediaControllerCompat().getPlaybackState()); mMediaControllerCallback.onQueueChanged(getMediaControllerCompat().getQueue()); mMediaControllerCallback.onQueueTitleChanged(getMediaControllerCompat().getQueueTitle()); getMediaControllerCompat().registerCallback(mMediaControllerCallback); if (mContentSeekBar != null) { mContentSeekBar.setMediaPlayer(new PlayerControl(mFragmentActivity, null)); } } @Override public void onMediaBrowserConnectionSuspended() { mIsBind = false; } @Override public void onMediaBrowserConnectionFailed() { mIsBind = false; } private void showControllerUi() { Utils.stopAnimation(mControllerContainer); Utils.resetAlpha(mControllerContainer); mControllerContainer.setVisibility(VISIBLE); } private void showPlayUi() { Utils.stopAnimation(mColumnPlayPause); Utils.resetAlpha(mColumnPlayPause); mColumnPlayPause.setVisibility(VISIBLE); switchToPlay(); } private void resetPlayPauseUiWithControllerVisibility() { if (mColumnPlayPause.getVisibility() != mControllerContainer.getVisibility()) { mColumnPlayPause.setVisibility(mControllerContainer.getVisibility()); } } private void switchToPlay() { mColumnPlay.setVisibility(VISIBLE); mColumnReplay.setVisibility(INVISIBLE); mColumnPause.setVisibility(INVISIBLE); } private void switchToPause() { mColumnPlay.setVisibility(INVISIBLE); mColumnReplay.setVisibility(INVISIBLE); mColumnPause.setVisibility(VISIBLE); setDvrPlaybackAvailableVisibility(INVISIBLE); } private void switchToReplay() { Bundle liveBundle = (mLiveBundle != null) ? mLiveBundle : getMediaControllerCompat().getExtras(); int broadcastStateV2 = liveBundle.getInt(LIVE_EXTRA_BROADCAST_STATE_V2, BROADCAST_STATE_UNKNOWN); if (broadcastStateV2 == BROADCAST_STATE_DVR_PLAYBACK_AVAILABLE && mIsLiveSeekable) { setDvrPlaybackAvailableVisibility(VISIBLE); refreshLiveDvrUiStatus(PLAYBACK_MODE_LIVE_DVR); } else { mColumnReplay.setVisibility(VISIBLE); } mColumnPlay.setVisibility(INVISIBLE); mColumnPause.setVisibility(INVISIBLE); } private void switchMode(boolean isLive, boolean isLiveSeekable) { mIsLive = isLive; mIsLiveSeekable = isLiveSeekable; setPlaybackMode(isLive ? PLAYBACK_MODE_LIVE_EDGE : PLAYBACK_MODE_VOD); setColumnContentSeekBarMargin(); if (isLive) { setContentSeekBarVisibility(mIsLiveSeekable ? VISIBLE : GONE); setSummaryViewerVisibility(INVISIBLE); setSwitchSpeedViewVisibility(GONE); setTextTrackToggleViewVisibility(GONE); setTextTrackViewVisibility(GONE); setBottomLeftColumnToLiveIcon(true); } else { setContentSeekBarVisibility(VISIBLE); setSummaryViewerVisibility(VISIBLE); setSwitchSpeedViewVisibility(VISIBLE); setTextTrackToggleViewVisibility(VISIBLE); setTextTrackViewVisibility(VISIBLE); removeViewFromCustomColumn(CUSTOM_COLUMN_BOTTOM_LEFT); } } private void refreshLiveDvrUiStatus(@PlaybackMode int playbackMode) { if (!mIsLiveSeekable) { return; } switch(playbackMode) { case PLAYBACK_MODE_LIVE_EDGE: case PLAYBACK_MODE_LIVE_DVR: setPlaybackMode(playbackMode); setBottomLeftColumnToLiveIcon(playbackMode == PLAYBACK_MODE_LIVE_EDGE); break; case PLAYBACK_MODE_VOD: default: break; } } private void setPlaybackMode(@PlaybackMode int playbackMode) { mPlaybackMode = playbackMode; if (mContentSeekBar != null) { mContentSeekBar.setPlaybackMode(mPlaybackMode); } } private void setColumnContentSeekBarMargin() { // workaround to place different margins for vod & live-dvr respectively int leftMargin = getResources().getDimensionPixelSize(R.dimen.progress_bar_column_left_margin); int rightMargin = getResources().getDimensionPixelSize(R.dimen.progress_bar_column_left_margin); if (mIsLiveSeekable) { leftMargin = getResources().getDimensionPixelSize(R.dimen.progress_bar_column_live_dvr_left_margin); rightMargin = getResources().getDimensionPixelSize(R.dimen.progress_bar_column_live_dvr_right_margin); } if (mColumnContentSeekBar.getLayoutParams() instanceof MarginLayoutParams) { MarginLayoutParams params = (MarginLayoutParams) mColumnContentSeekBar.getLayoutParams(); params.setMargins(leftMargin, 0, rightMargin, 0); mColumnContentSeekBar.setLayoutParams(params); } } private void setBottomLeftColumnToLiveIcon(boolean isLiveEdge) { TextView live = (TextView) View.inflate(mThemeContext, R.layout.live_view, null); Drawable drawable = VectorDrawableCompat.create(getResources(), isLiveEdge ? R.drawable.ic_live_player : R.drawable.ic_live_dvr_player, null); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(live, drawable, null, null, null); live.setTextColor(getResources().getColor(isLiveEdge ? R.color.color_live : R.color.color_live_dvr)); live.setOnClickListener(isLiveEdge ? null : mGrayLiveIconOnClickListener); setCustomViewToColumn(live, CUSTOM_COLUMN_BOTTOM_LEFT); mLivePositionTimeTextView = null; } private void setBottomLeftColumnToLivePositionTime() { mLivePositionTimeTextView = (TextView) View.inflate(mThemeContext, R.layout.live_view, null); setCustomViewToColumn(mLivePositionTimeTextView, CUSTOM_COLUMN_BOTTOM_LEFT); } }
feat : Add poster for vod
MediaCore/src/main/java/io/straas/android/media/demo/widget/StraasPlayerView.java
feat : Add poster for vod